List Comprehensions

General Syntax

 a = [ expr for x1 in s1
            for x2 in s2
            ...
            for xn in sn
            if fexpr ]

Expanded version

 a = [ ]
 for x1 in s1:
     for x2 in s2:
         ...
             for xn in sn:
                 if fexpr: a.append(expr)

Comments

  • The for operations are nested (not in parallel)
  • Syntax is a little mind-blowing at first
  • However, easy to use once you figure it out.
<<< O'Reilly OSCON 2001, New Features in Python 2, Slide 12
July 26, 2001, beazley@cs.uchicago.edu
>>>