list comprehensions
Elaine Jackson
elainejackson7355 at home.com
Wed Apr 7 16:15:26 EDT 2004
List comprehensions don't work the way you intuitively expect them to work. I
realize many people have no intuitions about how list comprehensions 'should'
work, so if you recognize yourself in this description, feel free to go back to
whatever you were doing before. If you're still here, though, I invite you to
consider the following definition:
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? Or even better: Can somebody tell me where to look in the
documentation to find out about list comprehensions? All donations gratefully
received.
Peace
More information about the Python-list
mailing list