§ 2.5.3section 13 of 18·~4 min
Comprehensions
A comprehension builds a new list in one line. Read it as: give me this, for each item, if a condition holds.
amounts = [499, 1299, 250, 80]
big = [a for a in amounts if a > 300]
with_gst = [round(a * 1.18) for a in amounts]
print(big)
print(with_gst)
OUTPUT
[499, 1299]
[589, 1533, 295, 94]The same idea works for dicts: {k: v.upper() for k, v in names.items()}.
watch out If a comprehension needs several conditions or won't fit on one line, write a normal loop. Code is read far more often than it's written.