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.
enumerate is really handy, since you can write shorter, more
concise code by using it.
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
>>> colors = ["red", "blue", "green"] >>> enumerate(colors) <enumerate object at 0x7f1b9dad05f0> >>> list(enumerate(colors)) [(0, 'red'), (1, 'blue'), (2, 'green')]
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
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
enumerate and you add an index before
l in the
>>> for i, l in enumerate(letters): ... print(i, l)
And that's it!