ASPN ActiveState Programmer Network
  ActiveState
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups | Web Services
SEARCH
advanced | search help

Reference
ActivePython 2.4
What's New
What's new in Python 2.4?
Contents
1 PEP 218: Built-In Set Objects
2 PEP 237: Unifying Long Integers and Integers
3 PEP 289: Generator Expressions
4 PEP 292: Simpler String Substitutions
5 PEP 318: Decorators for Functions and Methods
6 PEP 322: Reverse Iteration
7 PEP 324: New subprocess Module
8 PEP 327: Decimal Data Type
9 PEP 328: Multi-line Imports
10 PEP 331: Locale-Independent Float/String Conversions
11 Other Language Changes
12 New, Improved, and Deprecated Modules
13 Build and C API Changes
14 Porting to Python 2.4
15 Acknowledgements
About this document ...

MyASPN >> Reference >> ActivePython 2.4 >> What's New >> What's new in Python 2.4?
ActivePython 2.4 documentation

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:

PEP 322, Reverse Iteration
Written and implemented by Raymond Hettinger.

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

Privacy Policy | Email Opt-out | Feedback | Syndication
© ActiveState 2004 All rights reserved