[newbie] Iterating a list in reverse ?

Andy Dingley <dingbat@codesmiths.com> dingbat at codesmiths.com
Wed Jun 21 12:56:45 EDT 2006


Python newbie:  I've got this simple task working (in about ten
different ways), but I'm looking for the "favoured" and "most Python
like" way.

Forwards I can do this
for t in listOfThings:
    print t

Now how do I do it in reverse?   In particular, how might I do it if I
only wanted to iterate part-way through (with a conditional test and a
break), or if I had a large list ?

reverse( listOfThings )
for t in listOfThings:
    print t

As reverse() operates in-place I often can't do this. I'm also
(slightly) concerned about possible inefficiency issues of manipulating
a big list just to scan a peek at its tail.

Currently I'm doing this:

for i in range( len( listOfThings )-1, 0, -1):
    t = listOfThings  [i]
    print t

Is this the optimum ?   Would xrange() be a better choice (and when is
it a "big" list) ?



Thanks for any guidance




More information about the Python-list mailing list