enumerate() in python
enumerate(iterable,start=0)
Suppose there is a python list fruits which is defined as
>> fruits= [‘apple’,’banana’,’orange’]
Oftentimes, while solving coding problems, you would require to maintain a dictionary or a tuple which stores the index of the element and the element as a pair. For example, we would like to maintain a tuple called fruits_pos which stores the index of the fruit in the list fruits declared above as well as its name as a pair shown below.
fruits_pos = ((0,’apple’),(1,’banana’),(2,’orange’))
To build a tuple like fruit_pos from the list fruits, you take and empty tuple fruit_pos initially and you add each (index,name) pair while looping over the list.
Instead, python has provided a built-in function called enumerate(). The function takes an iterator ,sequence or some other object which supports iteration as the first argument. It also has a second argument start which is optional. By default, start is set to 0 i.e. the index of the first element starts from 0. If you want your object’s index to start from 1, then you pas 1 as the second argument.
So when you call enumerate() on the list fruits declared above, the output would be an enumerated object which you can use by converting it to a list or a tuple or a dictionary of enumerated elements.
>> fruits = [‘apple’,’banana’,’orange’]
>> list(enumerate(fruits))
[(0,’apple’),(1,’banana’),(2,’orange)]
>> tuple(enumerate(fruits,1))
((0,’apple’),(1,’banana’),(2,’orange))
If you have to implement enumerate() from scratch on your own, the code is something like this:
def enumerate(fruits,start=0):
i = start
for element in fruits:
yield i,element
i = i + 1
If you want to use enumerate() in loops:
>> fruits = [‘apple’,’banana’,’orange’]
>> for fruit in enumerate(fruits):
... print(fruit)
Output:
(0,'apple')
(1,'banana')
(2,'orange')