Python – Enumerate a List

Enumerate a List in Python

In Python, enumerate() takes a list as argument and adds a counter value to the list iterable.

In a For Loop, we can access the index of the item along with the element.

Using List Comprehension, we can convert the given list of items into a list of tuples, where each tuple contains the index and the respective item. 

Examples

Iterate over Enumerated List

In this example, we will take a list of strings, and iterate over the enumerated list, thus accessing both index (counter value) and element.

Python Program

fruits = ['apple', 'banana', 'mango', 'cherry']

for index, fruit in enumerate(fruits):
    print(index, ':', fruit)
Run

Output

0 : apple
1 : banana
2 : mango
3 : cherry

Enumerate List into a List of Tuples

In this example, we will take a list of strings, and create a list of tuples from this list to strings, where each tuple contains the index and respective item from the original list.

Python Program

fruits = ['apple', 'banana', 'mango', 'cherry']
result = [x for x in enumerate(fruits)]
print(result)
Run

Output

[(0, 'apple'), (1, 'banana'), (2, 'mango'), (3, 'cherry')]

Summary

In this tutorial of Python Examples, we learned how to enumerate a list using enumerate() builtin function.