Skip to content

python/comprehension-two-fors

Pack Severity Fix Versions
Python warning unsafe, with xpd check --fix --unsafe-fixes All versions

A comprehension with more than one for is hard to read. Write a nested loop, or flatten with [*xs for xs in lists] on Python 3.15.

def checks(cases):
return [check for case in cases for check in case.checks]
found = []
for case in cases:
found.extend(case.checks)
return found

The rule reports a comprehension or generator expression with more than one for.

Inside a function, xpd can write nested loops for a list or dict comprehension in a return, an assignment, or a call argument. The loop variables get fresh names when the originals would collide with other uses in the function. Generator expressions keep their lazy evaluation and require a manual rewrite.

Apply the fix with xpd check --fix --unsafe-fixes. The additional locals and the lifetime of their values are observable.

The clauses run in the order of a nested loop, but the result stands before both of them. A reader has to reorder the expression to follow it. On Python 3.15, [*case.checks for case in cases] flattens the lists with one for.

This comprehension has more than one for. Write a nested loop, or flatten with [*xs for xs in lists] on Python 3.15.

See all rules in the Python pack.