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.
1. Iterate over enumerated list
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.
fruits = ['apple', 'banana', 'mango', 'cherry'] for index, fruit in enumerate(fruits): print(index, ':', fruit)
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.
fruits = ['apple', 'banana', 'mango', 'cherry'] result = [x for x in enumerate(fruits)] print(result)
[(0, 'apple'), (1, 'banana'), (2, 'mango'), (3, 'cherry')]
In this tutorial of Python Examples, we learned how to enumerate a list using enumerate() builtin function.
- Python – Count the items with a specific value in the List
- How to Get List of all Files in Directory and Sub-directories?
- Python – How to Create an Empty List?
- Python List without Last Element
- Python List of Functions
- Python Program to Find Duplicate Items of a List
- Python Program to Find Largest Number in a List
- Python List of Dictionaries
- Python – Check if Element is in List
- How to Reverse Python List?