Enumerate() in Python
enumerate() function adds a counter to each item in a list or any other iterable, and returns a list of tuples containing the index position and the element for each element of the iterable.
It turns the iterable into something we can loop through using indexes, where each item comes with its number (starting from 0 by default).
Let's look at a simple example of an enumerate() with a list.
a = ["Geeks", "for", "Geeks"]
# Iterating list using enumerate to get both index and element
for i, name in enumerate(a):
print(f"Index {i}: {name}")
# Converting to a list of tuples
print(list(enumerate(a)))
Output
Index 0: Geeks Index 1: for Index 2: Geeks [(0, 'Geeks'), (1, 'for'), (2, 'Geeks')]
Explanation: enumerate(a) provides both the index (i) and the element (name) during iteration.
Syntax of enumerate() method
enumerate(iterable, start=0)
Parameters:
- Iterable: any object that supports iteration
- Start: the index value from which the counter is to be started, by default it is 0
Return:
- Returns an iterator containing a tuple of index and element from the original iterable
Using a Custom Start Index
By default enumrate() starts from index 0. We can customize this using the start parameter. if want the index to begin at value other than 0.
a = ["geeks", "for", "geeks"]
#Looping through the list using enumerate
# starting the index from 1
for index, x in enumerate(a, start=1):
print(index, x)
Output
1 geeks 2 for 3 geeks
Accessing the Next Element
In Python, the enumerate() function serves as an iterator, inheriting all associated iterator functions and methods. Therefore, we can use the next() function and __next__() method with an enumerate object.
a = ['Geeks', 'for', 'Geeks']
# Creating an enumerate object from the list 'a'
b = enumerate(a)
# This retrieves the first index-element pair
nxt_val = next(b)
print(nxt_val)
# This retrieves the second index-element pair
nxt_val = next(b)
print(nxt_val)
Output
(0, 'Geeks')
Each time the next() is called, the internal pointer of the enumerate object moves to the next element, returning the corresponding tuple of index and value.
Example Use Cases
1. Enumerating a Dictionary
We can use enumerate() with a dictionary to get both the index and its key-value pair:
d = {"a": 10, "b": 20, "c": 30}
# Enumerating through dictionary items
for index, (key, value) in enumerate(d.items()):
print(index, "-", key, ":", value)
Output
0 - a : 10 1 - b : 20 2 - c : 30
2. Enumerating a String
s = "python"
for i, ch in enumerate(s):
print(f"Index {i}: {ch}")
Output
Index 0: p Index 1: y Index 2: t Index 3: h Index 4: o Index 5: n
3. Enumerating a Set
s = {"apple", "banana", "cherry"}
for i, fruit in enumerate(s):
print(f"Index {i}: {fruit}")
Output
Index 0: apple Index 1: cherry Index 2: banana
Related Articles: