list comprehensions

Robert Brewer fumanchu at amor.org
Wed Apr 7 16:41:38 EDT 2004


Elaine Jackson wrote:
> List comprehensions don't work the way you intuitively expect 
> them to work.
>
> 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). For the sake of clarity, here 
> is workable code
> expressing the same intention:
> 
> def partitions(n):
>     reVal=[[n]]
>     for k in range(1,n):
>         for x in partitions(n-k):
>             reVal.append([k]+x)
>     return reVal
> 
> So I guess what I want to ask is: Can somebody explain the 
> semantics of list comprehensions to me?

Try reversing the loops:

>>> 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]]

When writing combined comprehensions, you write the "for" elements in
the same order they would be in the expanded code.


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org




More information about the Python-list mailing list