Re: [Python-ideas] Order of loops in list comprehension
On Oct 22, 2016 2:51 AM, "Alexander Heger"
For me the current behaviour does not seem unreasonable as it
resembles the order in which you write out loops outside a comprehension
That's true, but the main reason for having comprehensions syntax in the first place is so that it can be read declaratively -- as a description of the list you want, rather than a step-by-step sequence of instructions for building it up.
If you have to stop and mentally transform it into nested for-statements, that very purpose is undermined.
Exactly.
Well, an argument that was often brought up on this forum is that Python should do things consistently, and not in one way in one place and in another way in another place, for the same thing. Here it is about the order of loop execution. The current behaviour in comprehension is that is ts being done the same way as in nested for loops. Which is easy enough to remember. Same way, everywhere.
A strict interpretation by this logic would also require the [x ...] part to be at the end, like [... x] since that's how it would look in a nested for loop (inside deepest loop). I personally agree with what many others have said, in that comprehension order is not intuitive as is. I still page fault about it after many years of using. Is there a way to move the expression bit to the end in a backcompat way? It might be a completely different syntax though (I think both colons and semicolons were suggested). FWIW, Erlang/Elixir (sorry after 6 years python this is what I do now!) does it the same way as python:
[{X, Y} || X <- [1,2,3], Y <- [a,b]]. [{1,a},{1,b},{2,a},{2,b},{3,a},{3,b}]
Here X is the outer loop. I think the confusion stems from doing it both ways at the same time. We retain the for loop order but then hoist the expression to the top. Ideally we'd either not do that, or reverse the for loop order.
C Anthony Risinger wrote:
Erlang/Elixir (sorry after 6 years python this is what I do now!) does it the same way as python:
[{X, Y} || X <- [1,2,3], Y <- [a,b]]. [{1,a},{1,b},{2,a},{2,b},{3,a},{3,b}]
Here X is the outer loop.
I think the confusion stems from doing it both ways at the same time.
If the semicolon syntax I suggested were available, you'd be able to choose either order, and maybe even mix them in the one comprehension. Not sure if that's a good thing or not... -- Greg
participants (2)
-
C Anthony Risinger
-
Greg Ewing