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.
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.
fruits = ['apple', 'banana', 'mango', 'cherry'] for index, fruit in enumerate(fruits): print(index, ':', fruit)
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.
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.
- How to Get the list of all Python keywords?
- Python – Get Index or Position of Item in List
- Python – Check if Element is in List
- Python – List of Strings
- Python List without Last Element
- Python – Count the items with a specific value in the List
- Python Program to Find Unique Items of a List
- How to Check if Python List is Empty?
- Python Program to Find Smallest Number in List
- Python Program to Find Largest Number in a List