Getting number of iteration

  • Thread starter Florian Lindner
  • Start date
F

Florian Lindner

Hello,
when I'm iterating through a list with:

for x in list:

how can I get the number of the current iteration?

Thx,

Florian
 
B

Bill Mill

Hello,
when I'm iterating through a list with:

for x in list:

how can I get the number of the current iteration?

Python 2.4 and greater:

for n, x in enumerate(lst):
print "iteration %d on element %s" % (n, x)

Earlier:

n = 0
for x in lst:
print "iteration %d on element %s" % (n, x)
n += 1

And you shouldn't use list as a variable name; list() is a built-in
function which you'll clobber if you do.

Peace
Bill Mill
bill.mill at gmail.com
 
G

George Sakkis

Florian Lindner said:
Hello,
when I'm iterating through a list with:

for x in list:

how can I get the number of the current iteration?

Thx,

Florianfor

in python 2.3+:

for i,x in enumerate(sequence):
print "sequence[%d] = %s" %(i,x)


George
 
M

Mike Meyer

Bill Mill said:
Earlier:

n = 0
for x in lst:
print "iteration %d on element %s" % (n, x)
n += 1

Just for the record, the old idiom was:

for n in xrange(len(lst)):
x = lst[n]
print "iteration %d on element %s" % (n, x)

<mike
 
F

Fredrik Lundh

Mike said:
n = 0
for x in lst:
print "iteration %d on element %s" % (n, x)
n += 1

Just for the record, the old idiom was:

for n in xrange(len(lst)):
x = lst[n]
print "iteration %d on element %s" % (n, x)

it was? of the following four solutions,

for n in xrange(len(lst)):
x = lst[n]
...

for n in range(len(lst)):
x = lst[n]
...

n = 0
for x in lst:
...
n += 1

for x, n in enumerate(lst):
...

the xrange solution tends to be the slowest, especially for
relatively short lists (up to a 1000 elements, or so).

the exact details vary somewhat between Python versions,
but the += solution is always a good choice, and the xrange
solution is almost always a bad choice.

</F>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,176
Messages
2,570,950
Members
47,503
Latest member
supremedee

Latest Threads

Top