Skip to main content
Editor

Python Comprehensions: List, Dict, Set, and Generator in One Guide

Intermediate30 min9 exercises145 XP

Leer en españolЧитать на русскомLer em portuguêsอ่านภาษาไทย

0/9 exercises

Imagine you have a list of 100 numbers and you want a new list containing only the even ones, each doubled. With a regular loop, that takes four lines. With a Python comprehension, it takes one.

Comprehensions are one of Python's most loved features. They let you create new lists, dictionaries, and sets by describing what you want instead of writing step-by-step instructions for how to build it.

In this tutorial, you'll learn all four types of comprehensions - list, dict, set, and generator - along with filtering, conditionals, and the important question of when NOT to use them.

List Comprehensions: The Most Common Pattern

A list comprehension creates a new list by applying an expression to each item in an existing sequence. The syntax is: [expression for item in iterable].

Think of it as a compact for loop that builds a list. Instead of creating an empty list and appending inside a loop, you describe the result in a single line.

Regular loop (4 lines)
numbers = [1, 2, 3, 4, 5]
squares = []
for n in numbers:
    squares.append(n ** 2)
print(squares)  # [1, 4, 9, 16, 25]
List comprehension (1 line)
numbers = [1, 2, 3, 4, 5]
squares = [n ** 2 for n in numbers]
print(squares)  # [1, 4, 9, 16, 25]
Basic list comprehensions
# Square each number
numbers = [1, 2, 3, 4, 5]
squares = [n ** 2 for n in numbers]
print(squares)
# Convert names to uppercase
names = ['alice', 'bob', 'charlie']
upper_names = [name.upper() for name in names]
print(upper_names)
# Get the length of each word
words = ['hello', 'world', 'python', 'is', 'fun']
lengths = [len(w) for w in words]
print(lengths)
Output
[1, 4, 9, 16, 25]
['ALICE', 'BOB', 'CHARLIE']
[5, 5, 6, 2, 3]

Adding Conditions to Comprehensions

You can add an if clause to filter out items. Only items that pass the condition get included in the new list. The syntax is: [expression for item in iterable if condition].

Filtering with if
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Keep only even numbers
evens = [n for n in numbers if n % 2 == 0]
print(evens) # [2, 4, 6, 8, 10]
# Keep only words longer than 3 characters
words = ['hi', 'hello', 'hey', 'world', 'ok', 'python']
long_words = [w for w in words if len(w) > 3]
print(long_words) # ['hello', 'world', 'python']
Output
[2, 4, 6, 8, 10]
['hello', 'world', 'python']

You can also use an if-else expression to transform items differently based on a condition. But notice the syntax change - the if-else goes before the for, not after it.

Using if-else in comprehensions
numbers = [1, 2, 3, 4, 5, 6]
# Label each number as even or odd
labels = ['even' if n % 2 == 0 else 'odd' for n in numbers]
print(labels) # ['odd', 'even', 'odd', 'even', 'odd', 'even']
# Cap scores at 100
raw_scores = [85, 110, 92, 105, 78]
capped = [min(s, 100) for s in raw_scores]
print(capped) # [85, 100, 92, 100, 78]
Output
['odd', 'even', 'odd', 'even', 'odd', 'even']
[85, 100, 92, 100, 78]

Dict Comprehensions

Dict comprehensions work just like list comprehensions, but they create dictionaries. Use curly braces and a key: value expression. The syntax is: {key: value for item in iterable}.

Basic dict comprehensions
# Create a dict of numbers and their squares
squares = {n: n ** 2 for n in range(1, 6)}
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# Create a dict from two lists using zip()
names = ['Alice', 'Bob', 'Charlie']
scores = [95, 87, 72]
grade_book = {name: score for name, score in zip(names, scores)}
print(grade_book) # {'Alice': 95, 'Bob': 87, 'Charlie': 72}
Output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{'Alice': 95, 'Bob': 87, 'Charlie': 72}

You can also filter with if, just like list comprehensions. This is great for creating a subset of a dictionary.

Filtered and transformed dict comprehensions
prices = {'apple': 1.50, 'banana': 0.75, 'cherry': 3.00, 'date': 5.00}
# Keep only items under $2
affordable = {fruit: price for fruit, price in prices.items() if price < 2}
print(affordable) # {'apple': 1.5, 'banana': 0.75}
# Swap keys and values
flipped = {price: fruit for fruit, price in prices.items()}
print(flipped) # {1.5: 'apple', 0.75: 'banana', 3.0: 'cherry', 5.0: 'date'}
Output
{'apple': 1.5, 'banana': 0.75}
{1.5: 'apple', 0.75: 'banana', 3.0: 'cherry', 5.0: 'date'}

Set Comprehensions

Set comprehensions create sets - collections with no duplicates. The syntax uses curly braces just like dict comprehensions, but without the colon. The syntax is: {expression for item in iterable}.

Set comprehensions
# Get unique first letters from a list of names
names = ['Alice', 'Anna', 'Bob', 'Charlie', 'Chloe']
first_letters = {name[0] for name in names}
print(first_letters) # {'A', 'B', 'C'}
# Get unique word lengths
sentence = 'the quick brown fox jumps over the lazy dog'
lengths = {len(word) for word in sentence.split()}
print(sorted(lengths)) # [3, 4, 5]
Output
{'B', 'C', 'A'}
[3, 4, 5]

The key difference from list comprehensions is that sets automatically remove duplicates. Even though "Alice" and "Anna" both start with "A", the set only contains one "A".

Generator Expressions: Memory-Efficient Comprehensions

A generator expression looks like a list comprehension but uses parentheses instead of brackets. The big difference: it doesn't create all items at once. It generates them one at a time, on demand.

This matters when you're working with very large data. A list comprehension of a million items creates a million-item list in memory. A generator expression uses almost no memory - it computes each item only when you ask for it.

List comprehension vs generator expression
# List comprehension - builds the entire list in memory
squares_list = [n ** 2 for n in range(5)]
print(squares_list) # [0, 1, 4, 9, 16]
print(type(squares_list)) # <class 'list'>
# Generator expression - generates items on demand
squares_gen = (n ** 2 for n in range(5))
print(squares_gen) # <generator object ...>
print(type(squares_gen)) # <class 'generator'>
# You can loop through a generator
for sq in squares_gen:
print(sq, end=' ')
print()
Output
[0, 1, 4, 9, 16]
<class 'list'>
<generator object <genexpr> at 0x4fc5898>
<class 'generator'>
0 1 4 9 16

Generator expressions are commonly used inside functions like sum(), max(), and min(). You can skip the extra parentheses when the generator is the only argument.

Generator expressions inside functions
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Sum of squares using a generator (no extra parentheses needed)
total = sum(n ** 2 for n in numbers)
print(f'Sum of squares: {total}')
# Check if any number is negative
has_negative = any(n < 0 for n in numbers)
print(f'Has negative: {has_negative}')
# Check if all numbers are positive
all_positive = all(n > 0 for n in numbers)
print(f'All positive: {all_positive}')
Output
Sum of squares: 385
Has negative: False
All positive: True

Nested Comprehensions

You can put one for clause inside another to handle nested loops. The outer loop comes first, then the inner loop. This is useful for flattening lists or creating grids.

Flattening a nested list
# Flatten a list of lists
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
print(flat) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
# This is equivalent to:
flat2 = []
for row in matrix:
for num in row:
flat2.append(num)
print(flat2) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Creating coordinate pairs
# Create coordinate pairs
coords = [(x, y) for x in range(3) for y in range(3)]
print(coords)
# [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
Output
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

When NOT to Use Comprehensions

Comprehensions are powerful, but they're not always the right choice. If a comprehension is hard to read, a regular loop is better. Code clarity always wins over cleverness.

Avoid comprehensions when: the logic is complex with multiple conditions, you need side effects like printing inside the loop, or the comprehension spans more than about 80 characters wide.

Too complex: hard to read
result = [x * 2 if x > 0 else -x for x in data
         if x != 0 and x % 3 == 0]
Clear loop: easy to understand
result = []
for x in data:
    if x != 0 and x % 3 == 0:
        if x > 0:
            result.append(x * 2)
        else:
            result.append(-x)

Also, never use a comprehension purely for side effects. If you're calling print() or modifying an external variable, use a regular loop instead. A comprehension should always be about building a new collection.


Practice Exercises

Time to practice! These exercises cover all four comprehension types, from basic to more challenging patterns.

Exercise 1: Double Every Number
Write Code

Use a list comprehension to create a list called doubled that contains each number from the given list, multiplied by 2.

Expected output:

[2, 4, 6, 8, 10]
numbers = [1, 2, 3, 4, 5]
# Create doubled using a list comprehension
print(doubled)
Exercise 2: Filter Even Numbers
Write Code

Use a list comprehension with an if clause to create a list called evens that contains only the even numbers from the given list.

Expected output:

[4, 12, 8, 20, 6]
numbers = [3, 4, 7, 12, 8, 15, 20, 6, 9]
# Create evens using a list comprehension with filtering
print(evens)
Exercise 3: Predict the Output: if vs if-else
Predict Output

Read this code carefully and predict what it will print. Pay attention to where the if-else is placed.

Type the exact output.

nums = [1, 2, 3, 4, 5]
result = ['even' if n % 2 == 0 else 'odd' for n in nums]
print(result)
Exercise 4: Create a Dict Comprehension
Write Code

Use a dict comprehension to create a dictionary called name_lengths that maps each name to its length.

Expected output:

{'Alice': 5, 'Bob': 3, 'Charlie': 7}
names = ['Alice', 'Bob', 'Charlie']
# Create name_lengths using a dict comprehension
print(name_lengths)
Exercise 5: Unique Vowels with a Set Comprehension
Write Code

Use a set comprehension to find all unique vowels in the given word. Store the result in a variable called vowels_found, then print it sorted as a list.

Expected output:

['a', 'e', 'i', 'o']
word = 'conversation'
# Find unique vowels using a set comprehension
# Print them sorted
Exercise 6: Fix the Bug: Wrong Comprehension Syntax
Fix the Bug

This code tries to create a list where numbers above 5 are labeled 'high' and others are labeled 'low'. But the syntax is wrong and it crashes. Fix it.

Expected output:

['low', 'high', 'low', 'high', 'low', 'high']
nums = [3, 8, 2, 9, 1, 7]
result = ['high' for n in nums if n > 5 else 'low']
print(result)
Exercise 7: Refactor a Loop into a Comprehension
Refactor

Refactor the following loop into a single list comprehension. The output must stay exactly the same.

Expected output:

[1, 9, 25, 49, 81]
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
result = []
for n in numbers:
if n % 2 != 0:
result.append(n ** 2)
print(result)
Exercise 8: Flatten a Matrix
Write Code

Use a list comprehension with two for clauses to flatten the given matrix (a list of lists) into a single flat list. Then print the sum of all items using a generator expression inside sum().

Expected output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]
45
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Flatten using a list comprehension with nested for clauses
# Print the flat list
# Print the sum using a generator expression
Diagonal Sums
Stretch

A grid is a list of rows, all the same length, but it does not have to be square. Number the diagonals by adding the row and the column: the cell in row r, column c lies on diagonal r + c. Write a function diagonal_sums(grid) that returns the sum of each diagonal, from diagonal 0 (the top-left cell) to the last one (the bottom-right cell).

grid = [[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]]
diagonal_sums(grid)   # [1, 6, 15, 14, 9]

Here 6 is 2 + 4, and 15 is 3 + 5 + 7. An empty grid has no diagonals. Try to build the answer with comprehensions.

Return the answer instead of printing it: Check calls diagonal_sums() with its own grids, some of them hidden.

def diagonal_sums(grid):
pass
Solution unlocks after your first Check

Summary: What You Learned About Python Comprehensions

Here's a recap of everything you now know:

TypeSyntaxCreates
List comprehension[expr for x in items]A list
Filtered list[expr for x in items if cond]Filtered list
Transformed list[a if cond else b for x in items]Mapped list
Dict comprehension{k: v for x in items}A dict
Set comprehension{expr for x in items}A set (no dupes)
Generator expression(expr for x in items)A lazy generator
Nested comprehension[expr for a in X for b in a]Flattened list

Comprehensions are one of Python's signature features. They make your code shorter, more readable (when used well), and often faster than equivalent loops.

What's Next?

Now that you can create and transform collections with ease, you're ready to explore Python Tuples - immutable sequences that are perfect for fixed data like coordinates, records, and function return values.

You'll learn why immutability is useful, how tuple packing and unpacking work, and when to choose a tuple over a list.

Harder problems

More problems on this topic: Python idioms

Related Tutorials

Was this tutorial helpful?