Enumerate a List
Python - Enumerate a List
In Python, enumerate() builtin function can take a list iterable as argument and return an enumerated object created from the items in the list.
With the enumerated object in a For Loop, we can access the index of the items along with the items in the list.
Examples
1. Enumerate given list and iterate over it
In this example, we take a list of strings, and iterate over the enumerated list, thus accessing both index (counter value) and item in the list in the loop.
Python Program
fruits = ['apple', 'banana', 'mango', 'cherry']
for index, fruit in enumerate(fruits):
print(index, ':', fruit)
Output
0 : apple
1 : banana
2 : mango
3 : cherry
2. Convert enumerated list object into a list of tuples
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.
In this example, we will take a list of strings, and create a list of tuples from this list of strings, where each tuple contains the index and respective item from the given list of strings.
Python Program
fruits = ['apple', 'banana', 'mango', 'cherry']
result = [x for x in enumerate(fruits)]
print(result)
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.