0

I am talking about the order of the for in clauses.

This order works:

[print(element) for element_list in list_of_lists for element in element_list]

and this doesn't:

[print(element) for element in element_list for element_list in list_of_lists]

I personally find the second more readable.

jeroaranda
  • 61
  • 8
  • 4
    Why *wouldnt* you need a specific order? If either worked there would be ambiguity. See e.g. https://stackoverflow.com/a/45079294/3001761 for a visual explanation. – jonrsharpe Apr 06 '20 at 20:16
  • 4
    Yes, the order matters in a list comprehension. It is the same order as the equivalent for-loop, so it is consistent in that regard. Also, **you shouldn't be using a list comprehension here**. List comprehensions aren't for side-effects, like `print`ing. They are for *creating lists*. – juanpa.arrivillaga Apr 06 '20 at 20:16
  • could the compiler work with different orders for list comprehension and for loops? – jeroaranda Apr 06 '20 at 20:33

1 Answers1

1

Reason is quite simple. I guess we agree on lists being an ordered collection, so no issues there. Why the order? It's very simple to remember if you think it like this:

(elt for subl in lists for elt in subl)

is the same as

for subl in lists:
    for elt in subl:
        yield elt

So, all you need to do to change latter to former is to "unfold" nested for loop by removing colons, already right-indented block then slides to the right and the yield expression is put to the front.

If that is hard to start with, I recommend writing comprehensions so that you first write the loop parts, omit colons and newlines, and put the returned part there last. That is,

1.

for subl in lists
    for elt in subl

2.

[for subl in lists for elt in subl] , note "sliding" to right end

3.

[elt for subl in lists for elt in subl] Finished!

EdvardM
  • 2,934
  • 1
  • 21
  • 20
  • would it make sense to have different orders in list comprehension than in for loops? I find the incorrect way more readable. – jeroaranda Apr 06 '20 at 22:10
  • Understandable, I had it hard at first as well. "Wrong order" feels more natural, but it depends on how you see it; after realizing the rule I explained I find that totally fine. Also, if you refactor for loops to one-liners or vice versa in vim, there's less work with current syntax ;) – EdvardM Apr 06 '20 at 22:15