Python Principles

Python Enumerate Explained

In Python, enumerate() is a built-in function. It is used to compute the indexes of a list while iterating over it.

In other words, if you've ever found yourself looping over a list and needing the index of each element, then enumerate can help you.

Knowing about enumerate is really handy, since you can write shorter, more concise code by using it.

What exactly does enumerate do?

The enumerate function takes any sequence and gives you a sequence of tuples. The first item in each tuple is an index, and the second is the original item:

>>> colors = ["red", "blue", "green"]
>>> enumerate(colors)
<enumerate object at 0x7f1b9dad05f0>
>>> list(enumerate(colors))
[(0, 'red'), (1, 'blue'), (2, 'green')]

How to use enumerate

Here's an example:

>>> colors = ["red", "blue", "green"]
>>> for i, color in enumerate(colors):
...     print("color number %d is %s" % (i, color))
...
color number 0 is red
color number 1 is blue
color number 2 is green

In general, you iterate over enumerate(sequence) instead of just sequence, and then you use tuple unpacking to get the index along with the usual item.

So if you start with:

>>> letters = ["a", "b", "c"]
>>> for l in letters:
...     print(l)

Then you wrap letters in enumerate and you add an index before l in the loop:

>>> for i, l in enumerate(letters):
...     print(i, l)

And that's it!

Want to get better at Python?

Try our practical beginner lessons, or test your skills with our challenges.

View Lessons Try Challenges