Skip to main content

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

Intermediate30 min8 exercises115 XP
0/8 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
Loading editor...

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
Loading editor...

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
Loading editor...

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
Loading editor...

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
Loading editor...

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
Loading editor...

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
Loading editor...

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
Loading editor...

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
Loading editor...
Creating coordinate pairs
Loading editor...

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]
Loading editor...
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]
Loading editor...
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.

Loading editor...
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}
Loading editor...
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']
Loading editor...
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']
Loading editor...
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]
Loading editor...
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
Loading editor...

Summary: What You Learned About Python Comprehensions

Here's a recap of everything you now know:
---------
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](/python/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.