[Tutor] Nested list comprehensions

Kent Johnson kent37 at tds.net
Fri May 5 17:53:39 CEST 2006


John Clark wrote:
> Hello Tutors,
> 
> I am having trouble wrapping my mind around nested list
> comprehensions and am hoping that someone can either verify my
> thinking or provide insight as to what I am doing wrong.
> 
> If I weren't trying to use list comprehensions, I would
> code this as:
> 
> result = [] 
> for eachObject in C1:
>     for eachSubObject in eachObject.m():
>         result.append(eachSubObject)
> 
>  what I think I have come up with is: >
> result = [eachSubObject for eachObject in C1 for eachSubObject in eachObject.m()]

This is the correct equivalent.

> If this _is_ the correct syntax, this reads very awkwardly to me, and
> my initial reaction to this is that it should be expressed as:
> 
> result = [eachSubObject for eachSubObject in eachObject.m() for eachObject in C1] 

FWIW I think it is awkward too.

> However, in my testing, this doesn't appear to work.  If somone has a
> way of reading the nested list comprehension syntax that makes sense,
> I would appreciate it if you would share it.

I don't know if it makes sense, but the way I think of it is that list 
comps don't change the order of the 'for x in y' part of the loop, they 
just move the expression of what to add to the list to the beginning of 
the code.

Kent




More information about the Tutor mailing list