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.
Written by Stefan Arentz
Related protips
1 Response
Thx ! I was not aware of the second argument of enumerate. You mean things[idx] in your first example
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Python
Authors
Related Tags
#python
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#