A comprehension builds a list (or dict, or set) in one expression. It is a for loop that yields values.
Goal
Write list, dict, and set comprehensions, and keep a loop when the body is more than one line.
List
scores = [98, 91, 70, 95, 88]
print([s / 100 for s in scores])
print([s for s in scores if s >= 90])
print([name.upper() for name in ["Ada", "Alan", "Nia"]])With index
names = ["Ada", "Alan", "Grace"]
print([f"{i}. {n}" for i, n in enumerate(names, start=1)])Dict and set
names = ["Ada", "Alan", "Ada", "Grace"]
scores = [98, 91, 98, 95]
print({n: s for n, s in zip(["Ada", "Alan", "Grace"], [98, 91, 95])})
print({n.lower() for n in names})Nested (keep it short)
pairs = [(city, n) for city in ["Nairobi", "Mombasa"] for n in range(2)]
print(pairs)Two fors in one comprehension get hard to read. Use nested loops if you hesitate.
When a loop is clearer
rows = []
for name, score in [("Ada", 98), ("Alan", 91), ("Nia", 70)]:
if score < 90:
continue
rows.append({"name": name, "band": "A"})
print(rows)That is better as a loop because of continue plus a dict literal. Do not force a comprehension.
Pitfall
[print(x) for x in items] builds a list of None. Use a for loop for side effects.