Sometimes when we iterate over an iterable in Python such as a list, set, etc, we often need to know the index of the current object or keep the count of the iterations.

In such cases, the enumerate in Python comes in handy.

The enumerate() is a built-in method in Python that attach a counter to the iterable and returns it in the form of a enumerate object.

The general syntax for enumerate is:

enumerate(iterable, start)

Parameters

ParameterConditionDescription
iterableRequiredAn iterable (e.g. list, tuple, set etc.)
startOptionalStarting number for the counter.
Default is 0.
Python enumerate() function parameters

The start parameter for enumerate method is optional. It is used to mark the starting number of the counter/iterations.

Examples using enumerate()

>>> my_list = ["Harry Potter", "Rambo", "Avengers"]
>>> obj = enumerate(my_list)
>>> print(type(obj))
<class 'enumerate'>
>>> print(list(obj))
[(0, 'Harry Potter'), (1, 'Rambo'), (2, 'Avengers')] 

As we can see the object returned by the enumerate method is of type enumerate.

Also, when we contruct a list of the enumenrate object, we see the pairs of list elements with their respective indexed values.

Let’s see some examples using enumerate function for a better understanding.

>>> my_list = ["Harry Potter", "Rambo", "Avengers"]
>>> for i, movie in enumerate(my_list):
...     print(i,": ",movie)
0 :  Harry Potter                                                                                    
1 :  Rambo                                                                                           
2 :  Avengers

If we assign a value to the start parameter as 1, then the counting starts from 1:

>>> my_list = ["Harry Potter", "Rambo", "Avengers"]
>>> for i, movie in enumerate(my_list, start=1):
...     print(i,": ",movie)
1 :  Harry Potter                                                                                    
2 :  Rambo                                                                                           
3 :  Avengers

In conclusion, the enumerate is a built-in method in Python that associate a index value to the each of the items of the iterable object.

Leave a Reply