List Comprehensions

Examples

 a = [ 1, 4, -10, 20, -2, -5, 8 ]
 b = [ 2*x for x in a ]         # b = [2, 8, -20, 40, -4, -10, 16]
 c = [ x for x in a if x > 0 ]  # c = [1, 4, 20, 8]
 d = [ float(x) for x in f.readlines() ]
 

Creating tuples

 d = [ (x,y) for x in a for y in b ]
 
  • The (x,y) syntax is required.
  • In contrast to tuples without parentheses.
     # Syntax error
     d = [ x,y for x in a for y in b]
     
<<< O'Reilly OSCON 2001, New Features in Python 2, Slide 13
July 26, 2001, beazley@cs.uchicago.edu
>>>