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:

Parameters

Python enumerate() function parameters
ParameterConditionDescription
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.

output:

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.

Examples

Let’s see some examples before you get lost.

output:

Now if we assign a value to the start parameter as 1 then the counting starts from 1.

output:

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

Leave a Reply