Get number of iteration

Peter Otten __peter__ at web.de
Thu Jan 29 11:28:41 EST 2004


Florian Lindner wrote:

> If I iterate through a list, is there a way I can get the number of the
> iteration: first, second, third, ...
> 
> l = ["three", "four", "five", "six"]
> for x in l
>   print x
>   print x.iteration()  # <- That's what I'm looking for!
>   print "next"

>>> sample = "tree for five".split()
>>> for index, item in enumerate(sample):
...     print index, item
...
0 tree
1 for
2 five

You are looking for enumerate(). Counting starts at 0, though.

Peter



More information about the Python-list mailing list