Section 2.14. List Comprehensions


2.14. List Comprehensions

These are just fancy terms to indicate how you can programmatically use a for loop to put together an entire list on a single line:

  >>> squared = [x ** 2 for x in range(4)]   >>> for i in squared:   ...    print i   0   1   4   9


List comprehensions can do even fancier things like being selective of what to include in the new list:

  >>> sqdEvens = [x ** 2 for x in range(8) if not x % 2]   >>>   >>> for i in sqdEvens:   ...    print i   0   4   16   36




Core Python Programming
Core Python Programming (2nd Edition)
ISBN: 0132269937
EAN: 2147483647
Year: 2004
Pages: 334
Authors: Wesley J Chun

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net