Last Updated: February 25, 2016
·
571
· st3fan

Indexed looping

Say you want to loop over a collection and take both the item index and the value. There many patterns for this:

This is the most basic one:

for idx in range(len(things)):
    print idx,things[idx]

This is one more creative:

for idx, val in zip(range(len(things)), things):
    print idx,val

Don't do that!

What most people don't know is that Python actually has a built-in function called enumerate that does exactly the right thing:

for idx,val in enumerate(things):
    print idx,val

There also is a second argument that lets you specify the starting index, in case you don't want a zero based one.

Available since Python 2.3.

1 Response
Add your response

Thx ! I was not aware of the second argument of enumerate. You mean things[idx] in your first example

over 1 year ago ·