# Long form
squares = []
for n in range(10):
squares.append(n * n)
# Comprehension — same result
squares = [n * n for n in range(10)]
Read it left to right: "a list of n * n for every n in range(10)."
evens = [n for n in range(20) if n % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
names = ["alice", "bob", "carol", "dave"]
short_upper = [n.upper() for n in names if len(n) < 5]
# ['ALICE', 'BOB', 'DAVE']
# dict
prices = {"a": 1, "b": 2, "c": 3}
doubled = {k: v * 2 for k, v in prices.items()}
# {'a': 2, 'b': 4, 'c': 6}
# set (no duplicates)
words = ["apple", "ant", "banana"]
first_letters = {w[0] for w in words}
# {'a', 'b'}
[expression for item in collection] = one-line list builder.if condition at the end to filter.Convert each loop to a list comprehension.
# 1
result = []
for n in range(20):
if n % 3 == 0:
result.append(n)
# 2
upper_names = []
for name in ["alice", "bob"]:
upper_names.append(name.upper())
# 3
totals = []
for r in [{"qty":3,"price":10}, {"qty":2,"price":15}]:
totals.append(r["qty"] * r["price"])