[Tutor] Nested list comprehensions

John Clark clajo04 at mac.com
Fri May 5 17:27:54 CEST 2006


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.

I have a list of objects C1 and each object in the list has a method m() that will return a list of sub-objects.  I would like to create a list that contains all sub-objects of all members of the C1 collection.  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)

I have looked at the examples in the books several times, but none of the examples on nested list comprehensions show situations where there is a dependency between the outer loop and the inner loop that are being compressed.   However, what I think I have come up with is: 

result = [eachSubObject for eachObject in C1 for eachSubObject in eachObject.m()]

I am already expecting the "just use the first syntax if that does what you want" answers - but in this case, I am trying to understand nested list comprehensions, so I would appreciate an explanation of the list comprehension syntax. 

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] 

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.

Thanks,
-John 



More information about the Tutor mailing list