Skip to content

Comprehensions in Python

Mastering Comprehensions in Python: A Comprehensive Guide

Comprehensions are one of Python’s most loved features. They let you build a list, dictionary, or set from an existing iterable in a single, readable line — replacing a multi-line forfor loop and append()append() call. In this guide, we’ll explore list, dictionary, and set comprehensions, add filtering conditions, and cover nested comprehensions.

What is a Comprehension?

A comprehension is a concise way to create a collection by transforming and filtering items from another iterable. Instead of writing a loop that appends to a list, you describe the result directly.

Compare the traditional loop with a list comprehension:

loop_vs_comprehension.py
# Traditional loop
squares = []
for x in range(5):
    squares.append(x * x)
print(squares)
 
# List comprehension - same result, one line
squares = [x * x for x in range(5)]
print(squares)
loop_vs_comprehension.py
# Traditional loop
squares = []
for x in range(5):
    squares.append(x * x)
print(squares)
 
# List comprehension - same result, one line
squares = [x * x for x in range(5)]
print(squares)

Output:

command
C:\Users\Your Name> python loop_vs_comprehension.py
[0, 1, 4, 9, 16]
[0, 1, 4, 9, 16]
command
C:\Users\Your Name> python loop_vs_comprehension.py
[0, 1, 4, 9, 16]
[0, 1, 4, 9, 16]

List Comprehension

A list comprehension builds a new list. It is written inside square brackets [][].

The syntax of a list comprehension in Python is as follows:

Syntax
[expression for item in iterable]
Syntax
[expression for item in iterable]
  • expression — what to put in the new list (often a transformation of itemitem).
  • item — the loop variable.
  • iterable — the source you loop over.
list_comp.py
fruits = ["apple", "banana", "cherry"]
 
# Uppercase every fruit
upper = [fruit.upper() for fruit in fruits]
print(upper)
list_comp.py
fruits = ["apple", "banana", "cherry"]
 
# Uppercase every fruit
upper = [fruit.upper() for fruit in fruits]
print(upper)

Output:

command
C:\Users\Your Name> python list_comp.py
['APPLE', 'BANANA', 'CHERRY']
command
C:\Users\Your Name> python list_comp.py
['APPLE', 'BANANA', 'CHERRY']

Adding a Condition (Filtering)

You can add an ifif clause at the end to keep only items that match a condition.

The syntax with a condition is as follows:

Syntax
[expression for item in iterable if condition]
Syntax
[expression for item in iterable if condition]
filter_comp.py
numbers = range(10)
 
# Keep only the even numbers
evens = [n for n in numbers if n % 2 == 0]
print(evens)
filter_comp.py
numbers = range(10)
 
# Keep only the even numbers
evens = [n for n in numbers if n % 2 == 0]
print(evens)

Output:

command
C:\Users\Your Name> python filter_comp.py
[0, 2, 4, 6, 8]
command
C:\Users\Your Name> python filter_comp.py
[0, 2, 4, 6, 8]

Conditional Expression (if-else)

To transform items differently based on a condition (rather than filter them out), put an if-elseif-else before the forfor. This is a ternary expression.

if_else_comp.py
numbers = range(5)
labels = ["even" if n % 2 == 0 else "odd" for n in numbers]
print(labels)
if_else_comp.py
numbers = range(5)
labels = ["even" if n % 2 == 0 else "odd" for n in numbers]
print(labels)

Output:

command
C:\Users\Your Name> python if_else_comp.py
['even', 'odd', 'even', 'odd', 'even']
command
C:\Users\Your Name> python if_else_comp.py
['even', 'odd', 'even', 'odd', 'even']

Dictionary Comprehension

A dictionary comprehension builds a dictionary. It uses curly braces {}{} and a key: valuekey: value pair.

The syntax of a dictionary comprehension is as follows:

Syntax
{key_expression: value_expression for item in iterable}
Syntax
{key_expression: value_expression for item in iterable}
dict_comp.py
numbers = [1, 2, 3, 4]
 
# Map each number to its square
squares = {n: n * n for n in numbers}
print(squares)
dict_comp.py
numbers = [1, 2, 3, 4]
 
# Map each number to its square
squares = {n: n * n for n in numbers}
print(squares)

Output:

command
C:\Users\Your Name> python dict_comp.py
{1: 1, 2: 4, 3: 9, 4: 16}
command
C:\Users\Your Name> python dict_comp.py
{1: 1, 2: 4, 3: 9, 4: 16}

A common use is swapping keys and values, or building a lookup from two lists with zip()zip():

dict_zip.py
names = ["Alice", "Bob"]
ages = [30, 25]
people = {name: age for name, age in zip(names, ages)}
print(people)
dict_zip.py
names = ["Alice", "Bob"]
ages = [30, 25]
people = {name: age for name, age in zip(names, ages)}
print(people)

Output:

command
C:\Users\Your Name> python dict_zip.py
{'Alice': 30, 'Bob': 25}
command
C:\Users\Your Name> python dict_zip.py
{'Alice': 30, 'Bob': 25}

Set Comprehension

A set comprehension builds a set (unique, unordered values). It uses curly braces {}{} like a dict, but with single values instead of pairs.

The syntax of a set comprehension is as follows:

Syntax
{expression for item in iterable}
Syntax
{expression for item in iterable}
set_comp.py
words = ["hi", "hello", "hey", "hi", "hello"]
 
# Unique word lengths
lengths = {len(word) for word in words}
print(lengths)
set_comp.py
words = ["hi", "hello", "hey", "hi", "hello"]
 
# Unique word lengths
lengths = {len(word) for word in words}
print(lengths)

Output:

command
C:\Users\Your Name> python set_comp.py
{2, 5, 3}
command
C:\Users\Your Name> python set_comp.py
{2, 5, 3}

Nested Comprehensions

You can use more than one forfor clause to loop over nested data, such as flattening a list of lists.

nested_comp.py
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
 
# Flatten the matrix into a single list
flat = [value for row in matrix for value in row]
print(flat)
nested_comp.py
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
 
# Flatten the matrix into a single list
flat = [value for row in matrix for value in row]
print(flat)

Output:

command
C:\Users\Your Name> python nested_comp.py
[1, 2, 3, 4, 5, 6, 7, 8, 9]
command
C:\Users\Your Name> python nested_comp.py
[1, 2, 3, 4, 5, 6, 7, 8, 9]

When to Use Comprehensions

Use a comprehension when…Avoid a comprehension when…
The logic fits on one readable lineThe logic needs many conditions or side effects
You are transforming or filtering an iterableYou need try/excepttry/except inside the loop
Building a new list, dict, or setYou only loop for side effects (just use a forfor loop)

Visualize it

A comprehension like [x*10 for x in nums if x % 2 == 0][x*10 for x in nums if x % 2 == 0] is a little pipeline: each item is filtered by the ifif, and whatever survives is transformed by the expression and dropped into the new list. Watch it build the result one item at a time:

sketch [x*10 for x in nums if x % 2 == 0] p5.js
Each item passes through the filter, then the transform, into the result list.

Conclusion

Comprehensions provide a compact, expressive way to build lists, dictionaries, and sets directly from iterables. List comprehensions use [][], dictionary comprehensions use {key: value}{key: value}, and set comprehensions use {}{} with single values. You can add a trailing ifif to filter, a leading if-elseif-else to transform conditionally, and stack multiple forfor clauses to handle nested data. Used wisely, comprehensions make your code shorter and more readable. For more hands-on examples and in-depth tutorials, explore our resources on Python Central Hub!


Try it: Comprehensions Exercises

Exercise 1 – Basic List Comprehension

Exercise 2 – Comprehension with a Condition

Exercise 3 – Dictionary Comprehension

If this helped you, consider buying me a coffee ☕

Buy me a coffee

Was this page helpful?

Let us know how we did