list comprehensions

Daniel Dittmar daniel at dittmar.net
Wed Apr 7 16:55:34 EDT 2004


Elaine Jackson wrote:
> List comprehensions don't work the way you intuitively expect them to work. I

How can you say such a thing. 100 Haskell programmers have been asked 
about Python list comprehension and all found it intuitive.

> partitions = lambda n: [[n]]+[[k]+x for x in partitions(n-k) for k in
> range(1,n)]
> 
> As defined above, the function raises an exception when you call it ('k'
> referenced before assignment). 

Try a simpler example and you'll see the order of execution with nested 
loops:
 >>> [(a, x) for a in "ab" for x in "xy"]
[('a', 'x'), ('a', 'y'), ('b', 'x'), ('b', 'y')]

> So I guess what I want to ask is: Can somebody explain the semantics of list
> comprehensions to me? Or even better: Can somebody tell me where to look in the
> documentation to find out about list comprehensions? All donations gratefully
> received.

http://www.python.org/doc/2.3.3/ref/lists.html, especially "each of the 
for or if clauses a block, nesting from left to right".

 >>> partitions = lambda n: [[n]]+[[k]+x for k in range(1,n) for x in 
partitions(n-k)]
 >>> partitions (3)
[[3], [1, 2], [1, 1, 1], [2, 1]]

Daniel



More information about the Python-list mailing list