List, Dict & Set Comprehensions

Published by Brayan K

Building a new collection from an old one — squaring numbers, filtering out bad rows, flipping a dictionary — is something you'll do dozens of times a day. Comprehensions turn that three-line loop into one expressive, readable line.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

A loop that builds a list, in one line

In Loops - For and While, a loop built a new list from an old one, keeping the numbers that weren't negative. A list comprehension says the same thing in one line:

numbers = [1, -2, -3, 4]
kept = []
for n in numbers:
    if n >= 0:
        kept.append(n)
print(kept)

kept = [n for n in numbers if n >= 0]
print(kept)

# ✅ Expected output:
# [1, 4]
# [1, 4]

Read it in the same order as the loop: n, for each n in numbers, if n is at least 0. The part before for says what goes into the new list, the for says where the values come from, and the if, which is optional, says which ones to keep. The square brackets make the result a list.

Change each item, keep some, or both

The part at the front can be any expression, and the if any condition:

nums = [1, 2, 3, 4, 5, 6]
print([n * 2 for n in nums])
print([n for n in nums if n % 2 == 0])
print([n * n for n in nums if n > 3])

names = ["ada", "grace", "linus"]
print([name.title() for name in names])
print(names)

# ✅ Expected output:
# [2, 4, 6, 8, 10, 12]
# [2, 4, 6]
# [16, 25, 36]
# ['Ada', 'Grace', 'Linus']
# ['ada', 'grace', 'linus']

These are the two jobs Lambda Functions did with map() and filter(). A comprehension makes a new list and leaves the old one alone, as the last line shows, so store the result if you want to keep it: names = [name.title() for name in names]. It's for building a list, not for doing something to each item: [print(n) for n in nums] does print, but it also builds a list of Nones that nobody wants. Use a plain loop for that.

Where the if goes

An if after the for is a filter: the items that fail it are left out. To keep every item but change some of them, you need x if condition else y, which picks one of two values. It's called a conditional expression, and it goes at the front, where each value is made:

nums = [3, -1, 4, -5]
print([n for n in nums if n > 0])
print([n if n > 0 else 0 for n in nums])

# ✅ Expected output:
# [3, 4]
# [3, 0, 4, 0]

Mix them up and the line won't run. An else after the filter, as in [n for n in nums if n > 0 else 0], gives SyntaxError: invalid syntax, and an if at the front without its else gives this:

nums = [3, -1, 4, -5]
print([n if n > 0 for n in nums])

# ✅ Expected error:
# SyntaxError: expected 'else' after 'if' expression

Conditional Expressions (Ternary) covers x if condition else y on its own.

The variable stays inside the brackets

After a for loop, the loop variable keeps the last value it was given, as Loops - For and While showed. A comprehension's variable is different: it exists only inside the brackets, and a variable with the same name outside isn't touched:

k = 99
squares = [k * k for k in range(3)]
print(squares)
print(k)

# ✅ Expected output:
# [0, 1, 4]
# 99

Without the first line, there's no k outside the comprehension at all:

squares = [k * k for k in range(3)]
print(squares)
print(k)

# ✅ Expected output:
# [0, 1, 4]

# ✅ Expected error:
# NameError: name 'k' is not defined

Two for clauses read like nested loops

A comprehension can have more than one for. They run in the order you'd write the loops, outer first, so a list of lists flattens like this:

league = [["Ada", "Ben"], ["Cleo", "Dev"]]

names = []
for team in league:
    for name in team:
        names.append(name)
print(names)

print([name for team in league for name in team])

# ✅ Expected output:
# ['Ada', 'Ben', 'Cleo', 'Dev']
# ['Ada', 'Ben', 'Cleo', 'Dev']

Write the two clauses the other way round and the inner one runs first, before there's a team:

league = [["Ada", "Ben"], ["Cleo", "Dev"]]
names = [name for name in team for team in league]

# ✅ Expected error:
# NameError: name 'team' is not defined

If a variable called team is left over from an earlier loop, the swapped line runs instead, on the wrong data and with no error, so keep the clauses in the order of the loops. A comprehension can also build a list of lists. This is the one-line way to make rows that are separate lists, which Lists and Collections promised:

board = [[0] * 3 for i in range(2)]
board[0][0] = 5
print(board)

# ✅ Expected output:
# [[5, 0, 0], [0, 0, 0]]

Each pass makes a new [0] * 3, so the rows are two lists, not one list twice. The i is never used, and many people write _ for a name they don't need.

Dictionary and set comprehensions

Curly braces with key: value at the front make a dictionary, and with a single value, a set. Over a dictionary's .items(), from Dictionaries, each pass gets a key and its value:

stock = {"apples": 12, "pears": 0, "plums": 3}
print({name: n for name, n in stock.items() if n > 0})

prices = {"coffee": 3, "tea": 2, "juice": 3}
print({price: name for name, price in prices.items()})

print(sorted({len(w) for w in ["hi", "yo", "hey"]}))
tags = ["Tea", "cake", "TEA", "soup", "Cake"]
print(sorted({t.lower() for t in tags}))



# ✅ Expected output:
# {'apples': 12, 'plums': 3}
# {3: 'juice', 2: 'tea'}
# [2, 3]
# ['cake', 'soup', 'tea']

Turning the prices round lost coffee: two items cost 3, a key can appear only once, and the last one written wins. A set keeps one of each value, so the three lengths make two. A set of text has no fixed order, as Sets explained, so the last line sorts it. Leaving out .items() gives the "too many values to unpack" error from Dictionaries, and a comma where the colon belongs is a SyntaxError of its own:

prices = {"coffee": 3, "tea": 2}
by_price = {price, name for name, price in prices.items()}

# ✅ Expected error:
# SyntaxError: did you forget parentheses around the comprehension target?

Python guesses you meant a set of pairs, which would need (price, name) in brackets. For a dictionary, write price: name. Dictionary Methods Deep Dive has more ways to build and merge dictionaries.

Round brackets make a generator

With round brackets, the same syntax makes a generator expression. No list is built: each value is made only when something asks for the next one, and the values can be read only once:

squares = (n * n for n in range(4))
print(type(squares))
print(list(squares))
print(list(squares))

nums = [3, 1, 4]
print(sum(n * n for n in nums))
print(max(len(w) for w in ["hi", "hello", "hey"]))

# ✅ Expected output:
# <class 'generator'>
# [0, 1, 4, 9]
# []
# 26
# 5

The second list() is empty because the first one used up every value. A generator has no positions either, so squares[0] stops with a TypeError. As the only argument of a function such as sum() or max(), a generator expression needs no brackets of its own; next to a second argument it does, or Python stops with SyntaxError: Generator expression must be parenthesized. Generators & Iterators Mastery covers generators, and Booleans & Truthiness the any() and all() functions that are often given one.

Practice: tidy a list of words

Fill the three blanks with the values in the hint lines, in order: lowercase every word, make a set of the different words, and keep the words longer than three letters.

words = ["Tea", "cake", "TEA", "soup", "Cake"]
lower = [w.___() for w in words]
unique = ___w.lower() for w in words}
long = [w for w in lower if len(w) ___ 3]
print(lower)
print(sorted(unique))
print(long)

# 👉 replace ___ with lower
# 👉 replace ___ with {
# 👉 replace ___ with >

# ✅ Expected output:
# ['tea', 'cake', 'tea', 'soup', 'cake']
# ['cake', 'soup', 'tea']
# ['cake', 'soup', 'cake']

On your own: a day's orders

A café keeps its orders as (item, quantity) pairs: orders = [("tea", 2), ("cake", 1), ("tea", 3), ("soup", 0)]. With one comprehension each, print the items whose quantity is above 0, in order; the different items among those, sorted; and the total quantity, using sum(). You should get tea, cake and tea; cake and tea; and 6. Then compare with this solution:

orders = [("tea", 2), ("cake", 1), ("tea", 3), ("soup", 0)]
names = [item for item, qty in orders if qty > 0]
kinds = {item for item, qty in orders if qty > 0}
total = sum(qty for item, qty in orders)
print(names)
print(sorted(kinds))
print(total)

# ✅ Expected output:
# ['tea', 'cake', 'tea']
# ['cake', 'tea']
# 6

Each pair unpacks into item, qty, as in Tuples. The set drops the second tea, and the generator expression inside sum() adds up the quantities without building a list.

Practice quiz

nums = [3, -1, 4, -5]. What does [n for n in nums if n > 0] give?

  • [3, 4]
  • [3, 0, 4, 0]
  • [True, False, True, False]
  • [-1, -5]

Answer: [3, 4]. An if after the for is a filter: items that fail it are left out.

nums = [3, -1, 4, -5]. What does [n if n > 0 else 0 for n in nums] give?

  • [3, 4]
  • [3, 0, 4, 0]
  • [0, -1, 0, -5]
  • It stops with a SyntaxError

Answer: [3, 0, 4, 0]. if ... else at the front picks a value for every item, so nothing is left out.

squares = [k * k for k in range(3)], then print(k), with no other k in the program. What happens?

  • It prints 2
  • It prints [0, 1, 4]
  • It prints 4
  • It stops with NameError: name 'k' is not defined

Answer: It stops with NameError: name 'k' is not defined. A comprehension's variable exists only inside its brackets.

What does [name for team in [["Ada", "Ben"], ["Cleo"]] for name in team] give?

  • [['Ada', 'Ben'], ['Cleo']]
  • ['Cleo', 'Ada', 'Ben']
  • ['Ada', 'Ben', 'Cleo']
  • It stops with a NameError

Answer: ['Ada', 'Ben', 'Cleo']. The for clauses run like nested loops written in the same order: each team, then each name in it.

What does {v: k for k, v in {"a": 1, "b": 2, "c": 1}.items()} give?

  • {1: 'a', 2: 'b'}
  • {1: 'c', 2: 'b'}
  • {'a': 1, 'b': 2, 'c': 1}
  • It stops with an error

Answer: {1: 'c', 2: 'b'}. Two keys would be 1, and the last one written wins, so 1 ends up with 'c'.

What does {len(w) for w in ["hi", "yo", "hey"]} make?

  • A dictionary
  • A list
  • The set {2, 3}
  • The set {2, 2, 3}

Answer: The set {2, 3}. Braces with a single value make a set, and a set keeps one of each value.

squares = (n * n for n in range(3)), then list(squares) twice. What does the second list(squares) give?

  • []
  • [0, 1, 4]
  • None
  • It stops with an error

Answer: []. Round brackets make a generator, which can be read only once.

board = [[0] * 2] * 2, then board[0][0] = 5. What is board?

  • [[5, 0], [0, 0]]
  • [[0, 0], [0, 0]]
  • [[5, 5], [0, 0]]
  • [[5, 0], [5, 0]]

Answer: [[5, 0], [5, 0]]. Both rows are one list. [[0] * 2 for i in range(2)] makes two.

Continue this course

Frequently asked questions

When should I use a loop instead of a comprehension?

When the work is more than building a collection, such as printing, saving or several steps for each item. And when the comprehension stops reading as one idea, such as two for clauses plus two conditions. A loop with good names is easier to read than a line you have to take apart.

Are comprehensions faster than loops?

Usually a little, because the list is built without calling append() each time, but by how much changes from one Python version to another. Choose the one that reads better; Benchmarking with timeit shows how to measure your own case.

Is there a tuple comprehension?

No. Round brackets make a generator expression, not a tuple. To build a tuple the same way, pass a generator expression to tuple(), as in tuple(n * n for n in nums).

Related lessons