The enumerate() function in Python is a built-in function used to add a counter to an iterable object such as a list, tuple, or string. It returns an enumerate object, which produces pairs containing the index and the corresponding element from the iterable.
The enumerate() function is very useful when we need to access both the index and value of elements while iterating through a sequence, especially in loops.
enumerate(iterable, start=0)
Parameters
iterable Any iterable object such as a list, tuple, string, or dictionary.
start (optional) The starting value of the counter. By default, the counter starts from 0.
Return Value
fruits = ["apple", "banana", "mango"]
result = enumerate(fruits)
print(list(result))
Output
[(0, 'apple'), (1, 'banana'), (2, 'mango')]
Explanation
enumerate() assigns an index number to each element in the list.enumerate() in a Loopfruits = ["apple", "banana", "mango"]
for index, value in enumerate(fruits):
print(index, value)
Output
0 apple
1 banana
2 mango
Explanation
names = ["Rahul", "Amit", "Priya"]
for i, name in enumerate(names, start=1):
print(i, name)
Output
1 Rahul
2 Amit
3 Priya
Explanation
start parameter is set to 1.text = "Python"
for index, char in enumerate(text):
print(index, char)
Output
0 P
1 y
2 t
3 h
4 o
5 n
Explanation
numbers = (10, 20, 30)
for index, value in enumerate(numbers):
print(index, value)
Output
0 10
1 20
2 30
enumerate() is UsefulWithout enumerate():
fruits = ["apple", "banana", "mango"]
for i in range(len(fruits)):
print(i, fruits[i])
With enumerate():
for i, fruit in enumerate(fruits):
print(i, fruit)
Advantage
enumerate() is a built-in Python function.start parameter.