1. What Is a Comprehension?
A comprehension is a syntax construct provided by Python for building new containers from an existing iterable.
It can accomplish the following in a single expression:
- Iterate over data.
- Transform elements.
- Filter elements.
- Build new data structures.
- Handle nested data.
For example, create a list containing the squares of 1 through 5.
Traditional approach:
squares = []
for number in range(1, 6):
squares.append(number ** 2)
print(squares)
Output:
[1, 4, 9, 16, 25]
Using a list comprehension:
squares = [number ** 2 for number in range(1, 6)]
print(squares)
The output is the same:
[1, 4, 9, 16, 25]
A list comprehension combines iteration, computation, and adding elements into a single expression, reducing boilerplate code.
Common comprehensions in Python include:
| Type | Syntax form | Resulting type |
|---|---|---|
| List comprehension | [expression for variable in iterable] |
list |
| Dictionary comprehension | {key_expression: value_expression for variable in iterable} |
dict |
| Set comprehension | {expression for variable in iterable} |
set |
| Generator expression | (expression for variable in iterable) |
generator |
The first three are container comprehensions, while generator expressions use lazy evaluation and do not create the complete result list all at once.
2. List Comprehensions
A list comprehension is used to create lists quickly and is the most commonly used comprehension in Python.
1. Basic Syntax
[expression for item in iterable]
Meaning of each part:
expression: the expression used to generate elements in the list.item: the current element obtained during iteration.iterable: an iterable object, such as a list, tuple, string, set, orrange.
Execution logic:
flowchart TD
A["Start list comprehension"] --> B["Obtain iterable object"]
B --> C["Get next element"]
C --> D{"Are there more elements?"}
D -->|No| E["Return new list"]
D -->|Yes| F["Evaluate expression"]
F --> G["Add result to list"]
G --> C
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
2. Creating a Number List
numbers = [number for number in range(1, 6)]
print(numbers)
Output:
[1, 2, 3, 4, 5]
Here, number is used directly as the expression, so the elements in the new list are the same as the original iterated elements.
3. Transforming Elements
A list comprehension can do more than copy data; it can also perform calculations while generating a new list.
numbers = [1, 2, 3, 4, 5]
squares = [number ** 2 for number in numbers]
print(squares)
Output:
[1, 4, 9, 16, 25]
You can also convert Celsius temperatures to Fahrenheit:
```python celsius = [0, 10, 20, 30, 40] fahrenheit = [ temperature * 9 / 5 + 32 for temperature in celsius ] print(fahrenheit) ```Output:
```text [32.0, 50.0, 68.0, 86.0, 104.0] ```4. Filtering Elements with Conditions
A list comprehension can filter data using if.
Syntax:
```python [expression for item in iterable if condition] ```Only elements that satisfy the condition are evaluated by the expression and make it into the final list.
Example: filtering even numbers.
```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] evens = [ number for number in numbers if number % 2 == 0 ] print(evens) ```Output:
```text [2, 4, 6, 8] ```Example: filtering strings longer than 3 characters.
```python words = ["cat", "apple", "dog", "banana", "book"] result = [ word for word in words if len(word) > 3 ] print(result) ```Output:
```text ['apple', 'banana', 'book'] ```5. Using Transformation and Filtering Together
A comprehension can first check whether an element satisfies a condition, and then transform the elements that meet it.
```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] result = [ number ** 2 for number in numbers if number % 2 == 0 ] print(result) ```Output:
```text [4, 16, 36, 64] ```Order of execution:
- Take one element from the original data.
- Check whether the element satisfies the condition.
- If the condition holds, evaluate the expression.
- Add the computed result to the new list.
- Continue with the next element.
Note: the condition is written after the expression, but at execution time the condition is evaluated first, and only then is the expression computed.
6. Filtering with Multiple Conditions
You can combine multiple conditions in a comprehension using logical operators.
```python numbers = range(1, 21) result = [ number for number in numbers if number % 2 == 0 and number % 3 == 0 ] print(result) ```Output:
```text [6, 12, 18] ```You can also use multiple if clauses:
Multiple if clauses mean multiple filters applied one after another, which is equivalent to joining those conditions with and.
7. Using Conditional Expressions to Transform Elements
Note that if in a comprehension has two different uses.
The first is filtering elements:
```python result = [ number for number in range(1, 6) if number % 2 == 0 ] ```The second is deciding which value to produce based on a condition:
```python result = [ "偶数" if number % 2 == 0 else "奇数" for number in range(1, 6) ] print(result) ```Output:
```text ['奇数', '偶数', '奇数', '偶数', '奇数'] ```The difference between the two:
| Form | Effect |
|---|---|
for item in iterable if condition |
Decides whether an element is kept |
A if condition else B |
Decides which value is produced |
If a conditional expression has no else, it cannot be used directly as an ordinary conditional expression.
8. String Processing
Strings are iterable objects, so you can use list comprehensions on them directly.
text = "Python"
characters = [char for char in text]
print(characters)
Output:
['P', 'y', 't', 'h', 'o', 'n']
Convert to uppercase:
words = ["python", "java", "go"]
result = [
word.upper()
for word in words
]
print(result)
Output:
['PYTHON', 'JAVA', 'GO']
9. Nested List Comprehensions
List comprehensions can contain multiple for clauses to iterate over nested data.
Basic syntax:
[expression for item1 in iterable1 for item2 in iterable2]
For example, generate all combinations of elements from two lists:
colors = ["红色", "蓝色"]
sizes = ["S", "M", "L"]
combinations = [
(color, size)
for color in colors
for size in sizes
]
print(combinations)
Output:
[
('红色', 'S'),
('红色', 'M'),
('红色', 'L'),
('蓝色', 'S'),
('蓝色', 'M'),
('蓝色', 'L')
]
It is equivalent to:
combinations = []
for color in colors:
for size in sizes:
combinations.append((color, size))
The execution order of multiple for clauses is the same as that of traditional nested loops: the outer loop takes one element first, the inner loop iterates over all elements, and then the outer loop takes the next element.
10. Flattening a Two-Dimensional List
Suppose there is a two-dimensional list:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
It can be converted into a one-dimensional list using a nested list comprehension:
flat = [
number
for row in matrix
for number in row
]
print(flat)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Execution logic:
flowchart TD
A["Start processing a two-dimensional list"] --> B["Get a row of data"]
B --> C["Get an element from that row"]
C --> D{"Are there more elements in this row?"}
D -->|Yes| E["Add the element to the one-dimensional list"]
E --> C
D -->|No| F{"Is there another row?"}
F -->|Yes| B
F -->|No| G["Return the flattened list"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style F fill:#FFF5DE,stroke:#E8D29A,color:#334155
style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
If the nesting depth is not fixed, or the data structure is complex, it is recommended to use ordinary loops or recursive functions rather than piling all the logic into a single comprehension.
III. Dictionary Comprehensions
A dictionary comprehension is used to quickly create a dictionary and can generate both keys and values at the same time.
1. Basic Syntax
{
key_expression: value_expression
for item in iterable
}
It is similar to a list comprehension, but you need to construct dictionary elements in the form key: value.
2. Creating a Simple Dictionary
numbers = [1, 2, 3, 4, 5]
squares = {
number: number ** 2
for number in numbers
}
print(squares)
Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Here:
numberis the dictionary key.number ** 2is the dictionary value.
3. Create a dictionary from two lists
Suppose you have two lists, one holding names and one holding ages:
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 28]
You can pair them with zip(), then build a dictionary with a dictionary comprehension:
users = {
name: age
for name, age in zip(names, ages)
}
print(users)
Output:
{'Alice': 25, 'Bob': 30, 'Charlie': 28}
zip() stops by default when the shortest iterable is exhausted.
If you want to strictly check whether multiple input sequences have the same length, you can use strict=True, provided by Python 3.10 and later:
users = {
name: age
for name, age in zip(names, ages, strict=True)
}
If the lengths are inconsistent, a ValueError is raised, preventing data from being silently truncated.
4. Transform a dictionary
A dictionary itself can be iterated directly.
By default, iterating over a dictionary yields its keys:
scores = {
"Alice": 80,
"Bob": 90,
"Charlie": 75,
}
result = {
name: score + 10
for name, score in scores.items()
}
print(result)
Output:
{'Alice': 90, 'Bob': 100, 'Charlie': 85}
Here items() is used to get both keys and values.
5. Filter a dictionary with conditions
You can filter key-value pairs based on the values in a dictionary.
scores = {
"Alice": 85,
"Bob": 58,
"Charlie": 92,
"David": 66,
}
passed = {
name: score
for name, score in scores.items()
if score >= 60
}
print(passed)
Output:
{'Alice': 85, 'Charlie': 92, 'David': 66}
6. Transform keys and values
Dictionary comprehensions allow transforming both keys and values at the same time.
prices = {
"apple": 5,
"banana": 3,
"orange": 4,
}
result = {
name.upper(): price * 2
for name, price in prices.items()
}
print(result)
Output:
{'APPLE': 10, 'BANANA': 6, 'ORANGE': 8}
7. Swap dictionary keys and values
If the values in the dictionary are unique, you can reverse the key-value relationship with a dictionary comprehension.
original = {
"Alice": 1,
"Bob": 2,
"Charlie": 3,
}
reversed_dict = {
value: key
for key, value in original.items()
}
print(reversed_dict)
Output:
{1: 'Alice', 2: 'Bob', 3: 'Charlie'}
Note: if duplicate values exist in the original dictionary, the same key after reversal will be overwritten, and only the value corresponding to the last assignment will remain.
For example:
original = {
"Alice": 1,
"Bob": 1,
"Charlie": 2,
}
reversed_dict = {
value: key
for key, value in original.items()
}
print(reversed_dict)
Output:
{1: 'Bob', 2: 'Charlie'}
If you need to retain multiple keys corresponding to one value, you should group them using a list or set.
8. Nested Use of Dictionary Comprehensions
For example, organize student grades by class:
classes = {
"一班": ["Alice", "Bob"],
"二班": ["Charlie", "David"],
}
result = {
class_name: {
student: 0
for student in students
}
for class_name, students in classes.items()
}
print(result)
Output:
{
'一班': {'Alice': 0, 'Bob': 0},
'二班': {'Charlie': 0, 'David': 0}
}
This syntax can quickly build multi-level dictionary structures.
However, when there are too many nesting levels, it is recommended to split it into multiple steps to improve readability.
IV. Set Comprehensions
A set comprehension (Set Comprehension) is used to create sets.
Sets have two important characteristics:
- Elements are unique; duplicate elements are not retained.
- Sets do not guarantee a fixed iteration order of elements.
1. Basic Syntax
{
expression
for item in iterable
}
The main difference between set comprehensions and list comprehensions is that they use curly braces instead of square brackets.
2. Creating a Set
numbers = [1, 2, 3, 4, 5]
result = {
number
for number in numbers
}
print(result)
The output contains:
{1, 2, 3, 4, 5}
The actual display order of a set should not be used as a basis for program logic.
3. Automatically Removing Duplicate Elements
numbers = [1, 2, 2, 3, 3, 4, 5, 5]
unique_numbers = {
number
for number in numbers
}
print(unique_numbers)
The output contains:
{1, 2, 3, 4, 5}
Sets automatically remove duplicate elements.
4. Using Conditional Filtering
numbers = range(1, 11)
evens = {
number
for number in numbers
if number % 2 == 0
}
print(evens)
The output contains:
{2, 4, 6, 8, 10}
5. Transforming String Collections
words = ["python", "java", "python", "go", "java"]
unique_words = {
word.upper()
for word in words
}
print(unique_words)
The output contains:
{'PYTHON', 'JAVA', 'GO'}
6. Extracting Unique Elements from Multiple Lists
groups = [
["Alice", "Bob"],
["Bob", "Charlie"],
["Alice", "David"]
]
members = {
name
for group in groups
for name in group
}
print(members)
The output contains:
{'Alice', 'Bob', 'Charlie', 'David'}
Set comprehensions are suitable for deduplication, extracting members, and building sets of unique values.
However, if you need to preserve the order of the original data, you should not use a set directly. You can consider using a list together with dict.fromkeys() or similar methods for deduplication.
V. Differences Among the Three Types of Comprehensions
List, dictionary, and set comprehensions have similar syntax, but they generate different data structures.
1. Syntax Comparison
# List comprehension
list_result = [x * 2 for x in range(5)]
# Dictionary comprehension
dict_result = {x: x * 2 for x in range(5)}
# Set comprehension
set_result = {x * 2 for x in range(5)}
Result:
[0, 2, 4, 6, 8]
{0: 0, 1: 2, 2: 4, 3: 6, 4: 8}
{0, 2, 4, 6, 8}
2. Feature Comparison
| Comparison dimension | List comprehension | Dict comprehension | Set comprehension |
|---|---|---|---|
| Result type | list | dict | set |
| Syntax symbols | [] |
{key: value} |
{} |
| Are duplicate elements kept | Yes | Keys are unique | No |
| Is insertion order preserved | Yes | Yes | Not guaranteed |
| Is conditional filtering supported | Yes | Yes | Yes |
| Are nested loops supported | Yes | Yes | Yes |
| Is element indexing supported | Yes | Accessed by key | No |
3. How to Choose
Choose the comprehension based on the data structure you ultimately need:
- If you need an ordered sequence of data, use a list comprehension.
- If you need a key-value mapping, use a dict comprehension.
- If you need a collection of unique elements, use a set comprehension.
Do not choose an unsuitable data structure just to reduce the number of lines of code.
For example, if you later need to access elements in their original order, do not use a set comprehension merely because a set can remove duplicates automatically.
VI. Generator Expressions
Generator expressions have a syntax similar to list comprehensions, but use parentheses.
(expression for item in iterable)
It does not immediately generate a complete list; instead, it returns a generator object that produces elements one by one as the data is needed.
1. Basic Usage
List comprehension:
numbers = [number ** 2 for number in range(5)]
print(numbers)
Generator expression:
numbers = (number ** 2 for number in range(5))
print(numbers)
The output is similar to:
<generator object <genexpr> at ...>
You can retrieve the results one by one with next():
numbers = (number ** 2 for number in range(5))
print(next(numbers))
print(next(numbers))
print(next(numbers))
Output:
0
1
4
2. Iterating Over a Generator with for
numbers = (number ** 2 for number in range(5))
for number in numbers:
print(number)
Output:
0
1
4
9
16
A generator object is an iterator; it produces data step by step as you iterate over it.
Once iteration is complete, the generator is usually exhausted and cannot be iterated over again from the beginning like a list.
If you need to iterate again, you should create a new generator.
3. List Comprehensions vs. Generator Expressions
# Create the complete list immediately
squares_list = [x ** 2 for x in range(1000000)]
# Create a generator that computes on demand
squares_generator = (x ** 2 for x in range(1000000))
| Comparison dimension | List comprehension | Generator expression |
|---|---|---|
| Result type | list | generator |
| Computation method | Computed immediately | Computed on demand |
| Memory usage | Stores the complete result | Usually stores only the iteration state and the current result |
| Can it be iterated repeatedly | Yes | Usually cannot be iterated repeatedly directly |
| Is indexing supported | Yes | No |
| Use cases | When you need the complete result | Streaming processing of large data |
Note that a generator expression does not mean that none of the related data occupies memory.
For example:
numbers = (x ** 2 for x in [1, 2, 3, 4, 5])
Here the list [1, 2, 3, 4, 5] has already been created in advance. The generator only defers the computation of the squared values; it does not eliminate the memory overhead of the original list.
VII. Nesting and Execution Order of Comprehensions
A comprehension can contain multiple for and if clauses, but you need to understand their execution order.
1. Execution Order of Multiple for Clauses
result = [
(x, y)
for x in [1, 2]
for y in ["A", "B"]
]
print(result)
Output:
[(1, 'A'), (1, 'B'), (2, 'A'), (2, 'B')]
It is equivalent to:
result = []
for x in [1, 2]:
for y in ["A", "B"]:
result.append((x, y))
Therefore, multiple for clauses in a comprehension correspond from left to right to the nesting order of traditional loops.
2. Multiple for Clauses with if
result = [
(x, y)
for x in range(1, 4)
for y in range(1, 4)
if x != y
]
print(result)
Output:
[
(1, 2), (1, 3),
(2, 1), (2, 3),
(3, 1), (3, 2)
]
It first iterates over x, then over y, and then checks whether the combination meets the condition.
3. Conditional Expressions in Comprehensions
result = [
x if x > 0 else 0
for x in [-2, -1, 0, 1, 2]
]
print(result)