for-loop with index in Python

Everyday something new to learn :-) For quite some time now I’m coding mostly small scripts but also bigger stuff in Python (and now I’m also trying to get really into Django) and from time to time Python’s for-each preference to the C-style for loops sometimes got a little bit in my way.

For example: I have a list and I want to iterate over it but also know where I am during this loop. So until today I would have gone this road:

data = ('a','b','c')
i = 0
for f in data:
    print "%d => %s"%(i,f)

But today, while reading a litte bit in the Python Cookbook again, I discovered the enumerate object which make’s my own counter completely redundant :-)

data = ('a','b','c')
for i,f in enumerate(data):
    print "%d => %s"%(i,f)

I love those small things that make my life sooo much easier :D

comments powered by Disqus