
"Python's for loop are for looping over an iterable while doing something. So when I see a loop within a loop, I think "nested looping". I don't immediately think "we're building up a list-of-lists". I'd need to read through most of this code to figure out that's its purpose. Comprehensions are for specifically for building up new lists. So whenever I see a comprehension, I think "we're build a new list"."
"This is a list comprehension with another list comprehension inside its mapping part. List comprehensions create a new list, and since we've embedded a comprehension within a comprehension, this code creates a list-of-lists: I don't find this code very readable: But I don't think the comprehensions are the problem here. The problem is our use of whitespace. Here's the same code broken up over multiple lines: I find this code much more readable."
Nested list comprehensions produce a list-of-lists by embedding one comprehension inside another. Readability depends heavily on whitespace and how the comprehension is laid out across lines. Breaking a nested comprehension over multiple lines can make intent and structure clearer. Nested for-loops emphasize iterative control flow rather than the data structure being built. Using a comprehension signals list construction, making the resulting data structure more apparent at a glance. Combining an inner comprehension with an outer loop can be clearer than deeply nested loops. Avoid overly complex comprehensions that obscure intent.
Read at Pythonmorsels
Unable to calculate read time
Collection
[
|
...
]