LearnPy Hub
Data StructuresIntermediateLesson 12 of 32

Comprehensions

Watch the ideaBuild a list in one line
squares = [n * n for n in range(1, 5)]
range(1, 5)
1
2
3
4
squares

Take each n from range(1, 5) and put n * n into the new list.

1Level 1 · BasicsBasics

You'll often build a new list by looping over another one. A comprehension does that in a single, readable line. It's one of the things that makes Python code short and expressive.

From loop to comprehension

Here's the long way to make a list of squares:

squares = []
for n in range(1, 6):
    squares.append(n * n)

And the same thing as a list comprehension:

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

Read it left to right: "make n * n for each n in range(1, 6)". The square brackets mean the result is a list.

Filtering with if

Add an if at the end to keep only some items:

evens = [n for n in range(20) if n % 2 == 0]
long_words = [w for w in words if len(w) > 4]

Choosing a value with if/else

To transform every item in one of two ways, put the if/else at the front:

labels = ["even" if n % 2 == 0 else "odd" for n in nums]

Remember the difference: if at the end filters, if/else at the front chooses.

Dictionary and set comprehensions

lengths = {w: len(w) for w in words}      # dict
initials = {name[0] for name in names}    # set

Generator expressions

With round brackets inside a function call you don't even build a list: sum(n * n for n in range(1000)). This saves memory for large data.

Keep them readable

Comprehensions are great for simple transformations. If you need several conditions or nested loops, a normal for loop is often clearer, and clear code beats clever code.

Key points: [expr for x in items] builds a list; add if cond at the end to filter; put a if cond else b at the front to choose; use {k: v for ...} for dictionaries.

See it in actionOne line builds a whole list

Each comprehension makes a complete new list (or dictionary) in a single step.

Step-by-step

Try it yourselfExample 1: Loop vs comprehension

Both build exactly the same list.

example_1.py
Output appears here
Fill in the blanks

Squares in one line

Fill the blanks so the list holds the squares of 1 to 5: [1, 4, 9, 16, 25].

blanks.py
squares = [n  2  n in range(1, 6)]
print(squares)

Example 2: Filtering

The if at the end keeps only the items you want.

example_2.py
Output appears here
Fill in the blanks

Only long words

Fill the blank so only words longer than 3 letters are kept: ['apple', 'kiwis'].

blanks.py
words = ["fig", "apple", "kiwis", "pea"]
print([w for w in words  len(w) > 3])

Example 3: Choosing with if/else

Every item stays, but each is turned into one of two labels.

example_3.py
Output appears here
Fix the bug

if/else in the wrong place

This should label each number: ['odd', 'even', 'odd'] for [1, 2, 3]. Python reports an error. Fix the order.

buggy.py

Example 4: Dictionary and set comprehensions

Curly braces with key: value make a dictionary; without a colon they make a set.

example_4.py
Output appears here
Your turn

Shout the names

Using a list comprehension, turn names = ["mim", "joy", "tara"] into capitals and print ['MIM', 'JOY', 'TARA'].

my_code.py
Your turn

Name lengths

Use a dictionary comprehension to map each word to its length. For ["sun", "moon"] print {'sun': 3, 'moon': 4}.

my_code.py

2Level 2 · IntermediateNested comprehensions

Two for clauses

[(r, c) for r in range(2) for c in range(3)] reads like two nested loops, outer first. Use it for pairs, combinations and flattening.

Flattening

[x for row in grid for x in row] turns a list of lists into one list.

Comprehension inside a comprehension

[[r * c for c in range(1, 4)] for r in range(1, 4)] builds a 2-D table. The inner one makes a row; the outer repeats it.

Transposing

[list(col) for col in zip(*matrix)] turns rows into columns.

See it in actionFlattening step by step

Watch row and x change; x moves fastest, like an inner loop.

Step-by-step

Example 5: Tables, pairs and transposing

Change the ranges and see the shapes change.

example_5.py
Output appears here

3Level 3 · AdvancedGenerators, scope and when not to use them

Generator expressions save memory

Round brackets make a generator: sum(x * x for x in range(10**6)) computes items one at a time instead of building a million-item list. Use one whenever the result goes straight into sum, max, any, all or a loop.

Comprehensions have their own scope

The loop variable inside a comprehension doesn't leak out. But the walrus := lets you keep a computed value: [y for x in data if (y := x * x) > 50] works out x * x only once per item and keeps it.

Readability first

If a comprehension needs more than two fors, several conditions, or side effects like printing, write a normal loop. Comprehensions are for building values.

Example 6: List vs generator memory

The list stores all 100,000 numbers at once. The generator makes them one at a time, so it uses almost no memory, but it can only be used once.

example_6.py
Output appears here

Example 7: Scope and the walrus

Each average is worked out once and kept with :=, then reused as the value. The x inside the comprehension doesn't touch the x outside.

example_7.py
Output appears here
RememberThe position of if matters. [x for x in a if x > 0] drops items, while [x if x > 0 else 0 for x in a] keeps every item and changes some. Writing [x for x in a if x > 0 else 0] is a SyntaxError.
Exercise · predict the output

What does this print?

print([n * 2 for n in range(5) if n % 2 == 1])
Quick quiz · 5 questions
1. What does [c for c in "abc"] produce?
2. Which comprehension keeps only positive numbers from nums?
3. What kind of object does {w: len(w) for w in words} create?
4. What does [x * x for x in [1, 2, 3]] give?
5. What does ["big" if n > 5 else "small" for n in [3, 8]] give?
Ready to practice comprehensions?

50 graded problems are waiting in Topic Practice.

Practice this topic →
Python Comprehensions · LearnPy Hub