6 PEP 322: Reverse Iteration

Python 2.2

6 PEP 322: Reverse Iteration

A new built-in function, reversed(seq), takes a sequence and returns an iterator that loops over the elements of the sequence in reverse order.

>>> for i in reversed(xrange(1,4)):
...    print i
... 
3
2
1

Compared to extended slicing, such as range(1,4)[::-1], reversed() is easier to read, runs faster, and uses substantially less memory.

Note that reversed() only accepts sequences, not arbitrary iterators. If you want to reverse an iterator, first convert it to a list with list().

>>> input = open('/etc/passwd', 'r')
>>> for line in reversed(list(input)):
...   print line
... 
root:*:0:0:System Administrator:/var/root:/bin/tcsh
  ...

See Also:

Written and implemented by Raymond Hettinger.

See About this document... for information on suggesting changes.