When Not to Use Comprehensions
Comprehensions can become unreadable when too complex. If a comprehension spans more than two lines or has deeply nested logic, a regular loop is clearer.
Comprehensions can become unreadable when too complex. If a comprehension spans more than two lines or has deeply nested logic, a regular loop is clearer.
# Hard to read
result = [f(x) for x in data if g(x) and h(x) for y in x if y > 0]
# Better as a loop
result = []
for x in data:
if g(x) and h(x):
for y in x:
if y > 0:
result.append(f(x))
If you have to think hard to read the comprehension, use a loop.