[Tutor] Nested list comprehensions
Roel Schroeven
rschroev_nospam_ml at fastmail.fm
Sun May 7 15:52:38 CEST 2006
Alan Gauld schreef:
>> I am having trouble wrapping my mind around
>> nested list comprehensions
Me too: I feel it should be better with the order reversed.
>> and my initial reaction to this is that it should be expressed as:
>>
>> result = [eachSubObject for eachSubObject in eachObject.m() for
>> eachObject in C1]
That's what I initially expected too.
> My take on that is that it doesn't work from a scoping point of view.
> You have to fetch eachObject before you can send m() to it.
> Doing it the way you have it here would involve calling
> eachObject.m() before eachObject had been fetched from C1
Not exactly; to me, the above list comprehension is just an extension
from the way non-nested comprehensions work:
[2 * i for i in range(10)]
I interpret that as:
2 * i: we state an expression
for: we're going to evaluate that expression using the values that we're
going to define after this
i in range(10): which is, in this case, every i in range(10)
For the nested case, let's consider an admittedly contrived example:
a = range(10)
def f(n):
return [i + n*100 for i in range(10)]
I'd expect to be able to write
[j for j in f(i) for i in a]
Interpreting it as:
j: evaluate j for every value
for: in the sequence defined by
j in f(i): this expression, where f(i) is evaluated for every value
for: in
i in a: the sequence a
But that turns out to be the wrong way around. Not that if you literally
nest the list comprehensions (giving a list of lists instead of a flat
list as result), the order is as I would expect:
[[j for j in f(i)] for i in a]
So I would have expected that just dropping the inner [ and ] would
return the same thing, but flattened.
Actually I don't use nested list comprehensions all that often, and when
I do use them or encounter them I just remember that the for's should be
in the same order as in the non-LC solution.
--
If I have been able to see further, it was only because I stood
on the shoulders of giants. -- Isaac Newton
Roel Schroeven
More information about the Tutor
mailing list