3 ms·
The way to understand how the nesting works in the list comprehension: L = [] for x in X: for y in Y: L.append(x*y) [loops] translate t
by d0mine 11y ago
The way to understand how the nesting works in the list comprehension:
L = []
for x in X:
for y in Y:
L.append(x*y)
[loops] translate to
L = [x*y for x in X for y in Y]
If you understand the order of the loops in the first code fragment; you should understand the order in the second one -- it is the same order.
- dragonwriter 11y agoThe problem is that the relation of the body to the loop specifications is reversed, so the inner loop is most proximate to the body in the first, but most distant from the body in the second. The specification of the inner loop should always be most proximate to the body, not last independent of the location of the body.
- sanderjd 11y agoAs a person who thinks about this stuff in more functional terms, as in mapping over collections, rather than imperatively iterating and appending, it helps me to realize how it translates to map and flatMap rather than how it translates to for loops (which I already realized).