Reputation: 61
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.
Upvotes: 0
Views: 31
Reputation: 3072
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!
Upvotes: 1