Looping over a list using its indices is such a common operation that Python provides a built-in function called enumerate to help do it. Given a sequence—a list, a tuple, or a string—enumerate returns a list of pairs. The first element of each pair is an index, and the second is the sequence's value at that index.
>>> for x in enumerate( 'abc'): ... print x
>>> for x in enumerate([10, 20, 30]): ... print x
Using this gives us another way to write our double-the-values loop:
This is easier to read when we write it like this:
What's happening here is that Python actually allows multivalued assignment. If there are several variables on the left of an assignment statement and an equal number of values on the right, Python matches them up and does all the assignments at once:
This also works if the values on the right side are in a list, string, or other kind of sequences—Python "explodes" the sequence on the right and then assigns the elements to the variables on the left:
>>> first, second, third = [1, 2, 3] >>> first 1
>>> first, second, third = 'abc' >>> first 'a'
Knowing this, we can understand what happened in the for loop shown earlier:
On the first iteration of the loop, enumerate(values) produced the tuple (0, values). Python saw that the loop was using two variables as its indices, so it broke the tuple apart, assigning 0 to i and values to v. The next iteration produced 1, values[1 ], and so on.
Was this article helpful?