Python comprehensions allow for clean, concise, and efficient ways to generate sequences like lists, dictionaries, and sets. When you need to work with multiple levels of data, such as lists of lists or multi-dimensional structures, nested comprehensions become incredibly useful.
In this guide, we’ll explore how to write and use nested list and dictionary comprehensions in Python with clear examples and use cases.
1. What Are Nested Comprehensions?
Nested comprehensions are comprehensions inside comprehensions. They are used to handle multi-layered data structures and can often replace nested loops with more elegant and compact code.
2. Nested List Comprehensions
Example 1: Flattening a List of Lists
matrix = [[1, 2], [3, 4], [5, 6]]
flattened = [num for row in matrix for num in row]
print(flattened) # Output: [1, 2, 3, 4, 5, 6]
Example 2: Creating a Multiplication Table
table = [[i * j for j in range(1, 6)] for i in range(1, 6)]
for row in table:
print(row)
This creates a 5x5 multiplication table.
Example 3: Transposing a Matrix
matrix = [[1, 2, 3], [4, 5, 6]]
transposed = [[row[i] for row in matrix] for i in range(3)]
print(transposed) # Output: [[1, 4], [2, 5], [3, 6]]
Example 4: Filtering Nested Lists
nested = [[1, -1], [2, -2], [3, -3]]
positives = [[num for num in sublist if num > 0] for sublist in nested]
print(positives) # Output: [[1], [2], [3]]
Example 5: List of Tuples with Nested Loop
pairs = [(x, y) for x in range(3) for y in range(3)]
print(pairs) # Output: [(0, 0), (0, 1), ..., (2, 2)]
3. Nested Dictionary Comprehensions
Example 6: Creating a Nested Dictionary
nested_dict = {x: {y: x * y for y in range(1, 4)} for x in range(1, 4)}
print(nested_dict)
# Output: {1: {1: 1, 2: 2, 3: 3}, 2: {1: 2, 2: 4, 3: 6}, 3: {1: 3, 2: 6, 3: 9}}
Example 7: Nested Dictionary from Two Lists
students = ["Alice", "Bob"]
subjects = ["Math", "Science"]
scores = {student: {subject: 0 for subject in subjects} for student in students}
print(scores)
# Output: {'Alice': {'Math': 0, 'Science': 0}, 'Bob': {'Math': 0, 'Science': 0}}
4. Use Cases for Nested Comprehensions
- Flattening multi-dimensional data
- Transforming or filtering nested lists or dictionaries
- Generating multi-level data structures programmatically
- Matrix manipulations and transpositions
5. When Not to Use Nested Comprehensions
While nested comprehensions are powerful, they can become hard to read if overused or written without care. If your comprehension spans more than two levels or contains complex conditions, consider using nested loops for clarity.
6. Summary Table
Use Case | Example |
---|---|
Flatten List | [num for row in matrix for num in row] |
Matrix Creation | [[i * j for j in range(N)] for i in range(N)] |
Transpose Matrix | [[row[i] for row in matrix] for i in range(cols)] |
Nested Dict | {x: {y: val} for x in X for y in Y} |
7. Final Thoughts
Nested comprehensions are elegant tools for handling multi-layered data structures in Python. When used wisely, they can make your code shorter, cleaner, and more efficient. However, prioritize readability and maintainability—if it’s hard to understand at first glance, it might be better handled with traditional loops.