>>> my_list = [[[[1, 2, 3], [4, 5, 6], ]]]
>>> [a for d in my_list for c in d for b in c for a in b]
[1, 2, 3, 4, 5, 6]
is equivalent to
>>> my_list = [[[[1, 2, 3], [4, 5, 6], ]]]
>>> new_list = []
>>> for d in my_list:
... for c in d:
... for b in c:
... for a in b:
... new_list.append(a)
... print(new_list):
[1, 2, 3, 4, 5, 6]
This syntax seems backwards when read from left-to-right. According to PEP 202, "The form [... for x... for y...]
nests, with the last index varying fastest, just like nested for loops." is "the Right One."
It seems that this order (of left-to-right corresponding to outer-to-inner nested for loops) was chosen because that is the order in which nested for loops are written.
However, since the expression part of the list comprehension (a
in the above example), corresponds to the expression at the inner-most part of the nested loops (new_list.append(a)
in the above example), it seems to me that the for _ in _
closest to this expression should be the same in both cases, i.e. it should be for a in b
and on outwards:
>>> my_list = [[[[1, 2, 3], [4, 5, 6], ]]]
>>> [a for a in b for b in c for c in d for d in my_list]
NameError: name 'b' is not defined
so that the fastest-changing loop is closest to the action, so-to-speak. This also lends itself to being read from left-to-right in more logically stepwise fashion.
Is this a common sentiment among users? or does anyone have a good counter-argument as to why the current syntax implementation really is "the Right One"?
hemaj
, for example -- comes to SO and posts a question asking "Why is Python's list comprehension loop order backwards from the for loop order?"..for
loop ordering" is all the answer Guido would have needed. It would have taken a killer good reason to go against just that much.[a for b in my_list for a in b]
does something different from e.g.[a for a in (b for b in my_list)]
. The former is actually performing a flattening action onmy_list
, while the latter just unpacks and repacks the elements of (the elements of)my_list
. That's not obvious until you think about it.a
what is a? ah,a for a in b
, ok. but what is b? now we'd expecta for a in b for b in c
. makes sense, doesnt it?