Get number of iteration
Diez B. Roggisch
nospam-deets at web.de
Thu Jan 29 11:18:36 EST 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
value).
So usually x won't have an iteration-method. But of course you can alwas do
this:
for i in xrange(len(l)):
x = l[i]
print x
print i
print "next"
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
counter:
i = 0
for x in some_iterable_thingy:
print x
print i
i += 1
print "next"
Regards,
Diez
More information about the Python-list
mailing list