Python List Comprehensions
Master list, dict, set comprehensions and generator expressions with real examples.
What is a Comprehension?
A list comprehension is a concise, readable way to build a new list from an
existing sequence. Instead of writing a for loop that appends to an empty list, you express the
entire idea in one line inside square brackets: [expression for item in iterable].
Comprehensions run faster than equivalent loops because Python optimises them internally.
# Traditional loop — 4 lines squares = [] for x in range(1, 6): squares.append(x ** 2) print(squares) # List comprehension — 1 line, same result squares2 = [x ** 2 for x in range(1, 6)] print(squares2)
[1, 4, 9, 16, 25] [1, 4, 9, 16, 25]
Adding a Filter
Add an if clause to keep only items where the condition is True. This replaces a
for loop with an if inside it — the comprehension only processes items that pass the filter.
# Only even numbers evens = [x for x in range(20) if x % 2 == 0] print(evens) # Long words, uppercased words = ["cat", "elephant", "dog", "python"] long = [w.upper() for w in words if len(w) > 4] print(long)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18] ['ELEPHANT', 'PYTHON']
Dict and Set Comprehensions
The same syntax works for dictionaries (use {key: value for ...}) and sets
(use {expression for ...}). Dict comprehensions are great for transforming or
filtering existing dictionaries quickly.
# Dict comprehension: name → its length names = ["alice", "bob", "charlie"] lengths = {{n: len(n) for n in names}} print(lengths) # Set comprehension: unique squares nums = [1, 2, 2, 3] print({x**2 for x in nums})
{{'alice': 5, 'bob': 3, 'charlie': 7}}
{{1, 4, 9}}🧠 Quick Check
What does [x**2 for x in range(4)] produce?