Skip to content
Kuza Ndoto Academy

Comprehensions

Beginner → IntermediateChapter 4 · Page 24 of 564 min readUpdated 15 Nov 2026

A comprehension is a compact way to build a new list, dictionary or set from an existing sequence in a single, readable line. It replaces the common "create an empty list, loop, append" pattern and is one of the features that make Python code feel elegant.

From loop to list comprehension

Here is a normal loop that builds a list of squares:

squares = []
for n in range(1, 6):
    squares.append(n * n)
print(squares)
[1, 4, 9, 16, 25]

The same result as a list comprehension:

squares = [n * n for n in range(1, 6)]
print(squares)
[1, 4, 9, 16, 25]

Read it as "n * n, for each n in range(1, 6)". The general shape is:

[expression for item in iterable]

The expression at the front decides what goes into the new list; the for part says where the items come from. The original sequence is never changed.

names = ["  amina ", "BRIAN", "chebet  "]
clean = [name.strip().title() for name in names]
print(clean)

lengths = [len(name) for name in clean]
print(lengths)
['Amina', 'Brian', 'Chebet'] [5, 5, 6]

Filtering with if

Add if condition at the end to keep only the items that pass the test.

evens = [n for n in range(10) if n % 2 == 0]
print(evens)

prices = [450, 1200, 80, 3000, 650]
affordable = [p for p in prices if p <= 1000]
print(affordable)
[0, 2, 4, 6, 8] [450, 80, 650]

Choosing values with if…else

To transform every item in one of two ways (rather than filter), put a conditional expression at the front.

marks = [45, 72, 38, 90]
results = ["Pass" if m >= 50 else "Fail" for m in marks]
print(results)
['Fail', 'Pass', 'Fail', 'Pass']
Common mistake

Mixing up the two positions. A filter if goes at the end and has no else: [m for m in marks if m >= 50]. A choice if…else goes at the front: ["Pass" if m >= 50 else "Fail" for m in marks]. Writing [m if m >= 50 for m in marks] is a SyntaxError.

Dictionary comprehensions

Use curly braces and a key: value expression to build a dictionary.

names = ["Amina", "Brian", "Chebet"]
name_lengths = {name: len(name) for name in names}
print(name_lengths)

prices = {"tea": 30, "mandazi": 10, "chapati": 20}
doubled = {item: price * 2 for item, price in prices.items()}
print(doubled)

at_least_20 = {item: price for item, price in prices.items() if price >= 20}
print(at_least_20)
{'Amina': 5, 'Brian': 5, 'Chebet': 6} {'tea': 60, 'mandazi': 20, 'chapati': 40} {'tea': 30, 'chapati': 20}

Set comprehensions

Curly braces with a single expression (no colon) build a set, so duplicates vanish automatically.

remainders = {n % 3 for n in range(10)}
print(remainders)

emails = ["Amina@mail.com", "amina@mail.com", "brian@mail.com"]
unique = {e.lower() for e in emails}
print(sorted(unique))
{0, 1, 2} ['amina@mail.com', 'brian@mail.com']

Nested comprehensions

A comprehension can have more than one for. They run in the same order as nested loops written out in full, outer loop first. A common use is flattening a list of lists:

grid = [[1, 2], [3, 4], [5, 6]]
flat = [x for row in grid for x in row]
print(flat)

pairs = [(size, colour) for size in ["S", "M"] for colour in ["red", "blue"]]
print(pairs)
[1, 2, 3, 4, 5, 6] [('S', 'red'), ('S', 'blue'), ('M', 'red'), ('M', 'blue')]

Generator expressions

Replace the square brackets with round ones and you get a generator expression. It produces items one at a time instead of building a whole list in memory, which is ideal when you only need to feed the values into a function such as sum(), max() or any().

print(sum(n * n for n in range(1, 6)))
print(any(m < 40 for m in [45, 72, 38, 90]))
55 True

You'll learn how generators work on Iterators & Generators.

When not to use a comprehension

  • If it no longer fits comfortably on one or two lines, or needs several conditions, a normal loop is clearer.
  • Don't use a comprehension just for its side effects, such as [print(x) for x in items]. That builds a useless list of None values; use a plain for loop.
  • Readability always wins over cleverness. Your classmates (and your future self) should understand the line at a glance.
Note

The loop variable inside a comprehension, such as n in [n * n for n in range(5)], exists only inside the comprehension. It doesn't overwrite a variable called n outside it.

Key points

  • [expr for item in iterable] builds a new list in one line.
  • A filter if goes at the end; an if…else choice goes at the front.
  • {k: v for ...} builds a dictionary and {expr for ...} builds a set.
  • Round brackets make a memory-friendly generator expression, great inside sum() or any().
  • Prefer a normal loop when a comprehension gets long or complicated.
Up next · New chapter: FunctionsDefining FunctionsPackage code into reusable blocks.
→

Tip: use the ← and → keys to move between pages.