Nested comprehensions
A nested comprehension has more than one `for` in a row, and it reads in the same order as `for` loops written one inside the other.
Used in 20 lessons of the course, from Project 01.
A comprehension can have several for clauses. They read left to right, like nested loops: the first for is the outer one, the second is the inner one.
[x for row in rows for x in row] is the same as:
result = []
for row in rows:
for x in row:
result.append(x)
What you compute for each item goes at the front. That is why it's easy to get lost: the final value sits on the left, but it is produced in the innermost loop.
It is mostly used to flatten: turn a list of lists (or of tuples) into one collection.
The course uses it like this: {e.lower() for pair in re.findall(...) for e in pair}. re.findall returns pairs; the first for takes each pair and the second takes each string in the pair. The {} braces make the result a set.
If it's hard to read, write the plain loops first and then compress them.
Reach for it when: you need to flatten a list of lists or pairs while transforming each item. If you need three `for` clauses or long logic, use plain loops.
Examples
Common mistake
rows = [[1, 2], [3, 4]] flat = [x for x in row for row in rows] print(flat)
Why: The `for` clauses run in the order you would write them as nested loops. Here `row` is used before it exists.
How to write it: Put the outer loop first: [x for row in rows for x in row].
