Get number of iteration
Paul Prescod
paul at prescod.net
Thu Jan 29 11:31:12 EST 2004
Diez B. Roggisch 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"
> ...
>
> 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"
In recent versions of Python there is an easier way:
>>> for index, value in enumerate(["three", "four", "five", "six"]):
... print index, value
...
0 three
1 four
2 five
3 six
Paul Prescod
More information about the Python-list
mailing list