[newbie] Iterating a list in reverse ?
Fredrik Lundh
fredrik at pythonware.com
Wed Jun 21 13:08:15 EDT 2006
Andy Dingley <dingbat at codesmiths.com> wrote:
> 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
for item in reversed(listOfThings):
...
>>> help(reversed)
Help on class reversed in module __builtin__:
class reversed(object)
| reversed(sequence) -> reverse iterator over values of the sequence
|
| Return a reverse iterator
...
> As reverse() operates in-place I often can't do this.
given that lists only hold references to objects, reversing a *copy* of
the list is a lot more efficient than you may think...
</F>
More information about the Python-list
mailing list