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

poze 3 months ago362 gadeen

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.

Dyagnostik IA

Se IA ki fè l. Se pa yon repons — kominote a anba a konfime oswa korije l. Toujou verifye anvan ou fye l.

poze 3 months ago

1 Repons

3
✓
✓ Repons yo aksepte

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)

Konekte pou di lòt moun si li te mache.

answered 3 months ago

Sign in and verify your email to post an answer.