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

posée 3 months ago365 vuesen

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.

Diagnostic IA

Généré par IA. Ce n'est pas une réponse — la communauté ci-dessous le confirme ou le corrige. Vérifiez toujours avant de vous y fier.

posée 3 months ago

1 réponse

3
✓
✓ Réponse acceptée

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)

Connectez-vous pour dire si ça a marché.

answered 3 months ago

Sign in and verify your email to post an answer.