list comprehensions

Terry Reedy tjreedy at udel.edu
Wed Apr 7 17:42:00 EDT 2004


"Elaine Jackson" <elainejackson7355 at home.com> wrote in message
news:yjZcc.42823$Pk3.9547 at pd7tw1no...
>
> List comprehensions don't work the way you intuitively expect them to
work.

One of my pet posting peeves is when people ascribe their own
characteristics to others, as when they write 'you' when they really mean,
or should have meant, 'I'.  But nevermind.

> I realize many people have no intuitions about how list comprehensions
'should'
> work,

List comprehensions are sufficiently 'artificial' that I would advise
anyone to avoid the temptation to intuit how they work without consulting
the manual, tutorials, or other written explanations.

The Python Reference Manual Index, section L, entry List..comprehensions
takes one to subsection 5.2.4 List displays.  The last two sentences
therein read

 "When a list comprehension is supplied, it consists of a single expression
followed by at least one for clause and zero or more for or if clauses. In
this case, the elements of the new list are those that would be produced by
considering each of the for or if clauses a block, nesting from left to
right, and evaluating the expression to produce a list element each time
the innermost block is reached."

OK, takes a couple of readings and maybe some working examples.

> 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).

Of course, you have the two for clauses reversed, as the error message
might suggest to an experienced Pythoneer.  As the manual specifies, for/if
clauses nest *left to right*.  To match the double loop below, you want
instead

[[k]+x for k in range(1,n) for x in partitions(n-k)]

> def partitions(n):
>     reVal=[[n]]
>     for k in range(1,n):
>         for x in partitions(n-k):
>             reVal.append([k]+x)
>     return reVal

Terry J. Reedy







More information about the Python-list mailing list