Comprehensions are a great tool, but they are not always the best option. The golden rule: code is read many more times than it is written, so prioritize clarity over brevity.
When yes
Use them when the goal is to build a new collection from another one, with a simple transformation or filter:
# Clear and short
names = [w.strip().title() for w in lines]
evens = [n for n in numbers if n % 2 == 0]
lengths = {w: len(w) for w in words}
When not
If the comprehension becomes hard to read, use a normal loop. These are the warning signs:
- It has more than two nested
foror conditions. - It does not fit comfortably on a line (about 80-100 characters).
- You need to do more than build the collection: print, accumulate several values or modify external variables.
- You have to stop and think about how it reads.
# Hard to read
result = [x * y for x in range(10) if x % 2 == 0 for y in range(10) if y % 3 == 0 if x != y]
# Better with loops
result = []
for x in range(10):
if x % 2 != 0:
continue
for y in range(10):
if y % 3 == 0 and x != y:
result.append(x * y)
Do not use a comprehension just for its effects
A comprehension is for creating a list. If you only want to run something for each element, such as printing, use a for:
# Bad: creates a list of None that is not used
[print(n) for n in numbers]
# Good
for n in numbers:
print(n)
A list or a generator
When you are only going to go through the results once, for example to add them up, there is no need to create the list. Remove the brackets and use a generator expression:
total = sum([n ** 2 for n in range(1000)]) # creates a list of 1000 elements
total = sum(n ** 2 for n in range(1000)) # calculates it on the fly
Lambda in moderation
The same goes for lambda: it is ideal for short criteria for key, map or filter. If you need more than one expression or want to reuse the logic, write a named function:
def age_in_months(person):
return person["age"] * 12
people.sort(key=age_in_months)
Summary of decisions
| Situation | Best option |
|---|---|
| Transform or filter a collection in a simple way | comprehension |
| Logic with several steps or side effects | for loop |
| Add up, count or find the maximum on the fly | sum/max with a generator expression |
| Short sorting criterion | key=lambda ... |
| Long or reusable criterion | function with def |
If you have got this far you already write more Pythonic code. Review Double the positives and The best student to check it.