Sometimes when we iterate over any iterable such as a list or set we need to know the index of the current object or keep the count of the iterations.

In such cases, enumerate in python comes handy. enumerate() in python attach a counter to the iterable and returns it in the form of enumerate object.

The general syntax for enumerate is:



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

Let’s see in code what actually enumerate does in python.

my_list = ["Harry Potter", "Rambo", "Avengers"]

obj = enumerate(my_list)



[(0, 'Harry Potter'), (1, 'Rambo'), (2, 'Avengers')] 

As you can see the return type of the enumerate is an object of class enumerate and when we output the object by converting it into a list, we actually get a list of pairs of count and list’s elements.

Hence, we can use it for our benefits while looping through the iterable.


Let’s see some examples before you get lost.

my_list = ["Harry Potter", "Rambo", "Avengers"]

for i, movie in enumerate(my_list):
    print(i,": ",movie)


0 :  Harry Potter                                                                                    
1 :  Rambo                                                                                           
2 :  Avengers

Now 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

I hope you understood the basics of Python’s enumerate() function. If you have any doubts or suggestions then comment below.

Leave a Reply

eighteen + 19 =