Get number of iteration
Diez B. Roggisch
nospam-deets at web.de
Thu Jan 29 17:18:36 CET 2004
> 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"
No, this won't work - x is the value of the list element, not an c++-like
iterator-object (that has to be dereferenced before accessing the actual
So usually x won't have an iteration-method. But of course you can alwas do
for i in xrange(len(l)):
x = l[i]
Or - if len() can't be applied to your sequence for whatever reason, as it
is e.g. a iterable object, you can of course keep track with your own
i = 0
for x in some_iterable_thingy:
i += 1
More information about the Python-list