List comprehension vs for loop in Python: which is better?

asked 3 months ago364 viewsen

3

Is [x * 2 for x in nums if x > 0] better than a normal for loop with append? My code reviewer keeps suggesting comprehensions.

AI diagnosis

AI-generated. Not an answer — the community below confirms or corrects it. Always verify before relying on it.

asked 3 months ago

1 Answer

3
✓
✓ Accepted answer

For building a new list from an existing iterable, comprehensions are idiomatic, more concise, and a bit faster (no repeated .append attribute lookup).

positives_doubled = [x * 2 for x in nums if x > 0]

Use a regular loop when: - There are side effects (printing, writing to a DB). Don't use a comprehension just to loop. - The logic needs several statements, try/except, or would need nested conditions that hurt readability.

For large data you only iterate once, use a generator expression instead. It doesn't build the whole list in memory:

total = sum(x * 2 for x in nums if x > 0)

Sign in to tell others whether this worked.

answered 3 months ago

Sign in and verify your email to post an answer.