📘 Lesson 15 · Intermediate

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.

basic.py
# 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)
▶ Output
[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.

filter.py
# 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)
▶ Output
[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_set.py
# 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})
▶ Output
{{'alice': 5, 'bob': 3, 'charlie': 7}}
{{1, 4, 9}}
If a comprehension needs more than one or two conditions, use a regular for loop. Readability always wins over cleverness.

🧠 Quick Check

What does [x**2 for x in range(4)] produce?

[1, 4, 9, 16]
[0, 1, 4, 9]
[0, 2, 4, 6]
[1, 2, 3, 4]

Tags

list comprehensiondict comprehensionset comprehensiongeneratorone-liner