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:
# 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)# 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:
C:\Users\Your Name> python loop_vs_comprehension.py
[0, 1, 4, 9, 16]
[0, 1, 4, 9, 16]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:
[expression for item in iterable][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.
fruits = ["apple", "banana", "cherry"]
# Uppercase every fruit
upper = [fruit.upper() for fruit in fruits]
print(upper)fruits = ["apple", "banana", "cherry"]
# Uppercase every fruit
upper = [fruit.upper() for fruit in fruits]
print(upper)Output:
C:\Users\Your Name> python list_comp.py
['APPLE', 'BANANA', 'CHERRY']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:
[expression for item in iterable if condition][expression for item in iterable if condition]numbers = range(10)
# Keep only the even numbers
evens = [n for n in numbers if n % 2 == 0]
print(evens)numbers = range(10)
# Keep only the even numbers
evens = [n for n in numbers if n % 2 == 0]
print(evens)Output:
C:\Users\Your Name> python filter_comp.py
[0, 2, 4, 6, 8]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.
numbers = range(5)
labels = ["even" if n % 2 == 0 else "odd" for n in numbers]
print(labels)numbers = range(5)
labels = ["even" if n % 2 == 0 else "odd" for n in numbers]
print(labels)Output:
C:\Users\Your Name> python if_else_comp.py
['even', 'odd', 'even', 'odd', 'even']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:
{key_expression: value_expression for item in iterable}{key_expression: value_expression for item in iterable}numbers = [1, 2, 3, 4]
# Map each number to its square
squares = {n: n * n for n in numbers}
print(squares)numbers = [1, 2, 3, 4]
# Map each number to its square
squares = {n: n * n for n in numbers}
print(squares)Output:
C:\Users\Your Name> python dict_comp.py
{1: 1, 2: 4, 3: 9, 4: 16}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():
names = ["Alice", "Bob"]
ages = [30, 25]
people = {name: age for name, age in zip(names, ages)}
print(people)names = ["Alice", "Bob"]
ages = [30, 25]
people = {name: age for name, age in zip(names, ages)}
print(people)Output:
C:\Users\Your Name> python dict_zip.py
{'Alice': 30, 'Bob': 25}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:
{expression for item in iterable}{expression for item in iterable}words = ["hi", "hello", "hey", "hi", "hello"]
# Unique word lengths
lengths = {len(word) for word in words}
print(lengths)words = ["hi", "hello", "hey", "hi", "hello"]
# Unique word lengths
lengths = {len(word) for word in words}
print(lengths)Output:
C:\Users\Your Name> python set_comp.py
{2, 5, 3}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.
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)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:
C:\Users\Your Name> python nested_comp.py
[1, 2, 3, 4, 5, 6, 7, 8, 9]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 line | The logic needs many conditions or side effects |
| You are transforming or filtering an iterable | You need try/excepttry/except inside the loop |
| Building a new list, dict, or set | You 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:
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 coffeeWas this page helpful?
Let us know how we did
