Getting number of iteration

Fredrik Lundh fredrik at pythonware.com
Fri May 6 18:52:08 EDT 2005


Mike Meyer wrote:

> > 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>






More information about the Python-list mailing list