List Comprehensions

How to shoot yourself in the foot

  • Iteration variables used in list comprehensions are evaluated in "outer" scope.
     for i in s:
         ...
         t = [2*i for i in r]    # Overwrites outer i
         # Corrupted value of i
         ...
  • It is very easy to forget this fairly annoying side effect

How make heads explode (courtesy of Tim Peters)

 >>> d = range(3) 
 >>> x = [None] * 3 
 >>> base3 = [x[:] for x[0] in d for x[1] in d for x[2] in d]
 >>> base3
 [[0, 0, 0], [0, 0, 1], [0, 0, 2], 
  [0, 1, 0], [0, 1, 1], [0, 1, 2], 
  [0, 2, 0], [0, 2, 1], [0, 2, 2], 
 ...
<<< O'Reilly OSCON 2001, New Features in Python 2, Slide 14
July 26, 2001, beazley@cs.uchicago.edu
>>>