The enumerate Function

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 example:

Download loop/enumerate.cmd

>>> 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:

Download loop/enumerate_2.cmd

This is easier to read when we write it like this:

Download loop/enumerate_3.cmd

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:

Download loop/multi_assign.cmd

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:

Download loop/multi_assign_explode.cmd

>>> 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[0]). Python saw that the loop was using two variables as its indices, so it broke the tuple apart, assigning 0 to i and values[0] to v. The next iteration produced 1, values[1 ], and so on.

Was this article helpful?

0 0

Post a comment