Readability and Common Mistakes
In this tutorial, we'll learn when comprehensions help and when a normal loop is clearer.
Comprehensions are useful, but readability matters more than being clever.
This is readable:
numbers = [1, 2, 3]
doubled = [number * 2 for number in numbers]
This is harder to read:
result = [x * 2 for x in numbers if x > 0 if x % 2 == 0]
It may work, but a normal loop might be clearer.
Use Good Names
Avoid unclear names when the comprehension is not tiny:
squares = [number * number for number in numbers]
This is easier to read than:
squares = [x * x for x in numbers]
Short names are fine in simple examples, but descriptive names help beginners.
Do Not Use Comprehensions for Side Effects
Do not use a comprehension just to print:
[print(name) for name in names] # poor style
Use a normal loop:
for name in names:
print(name)
Comprehensions are for building collections.
Choose the Right Tool
Use:
- List comprehensions for lists
- Dictionary comprehensions for key-value pairs
- Set comprehensions for unique values
- Normal loops for multi-step logic
Practice
Rewrite one comprehension as a normal loop, then rewrite one normal loop as a comprehension. Compare which version is easier to read.