5
Lesson 5
Nested list comprehension
A nested list comprehension is a way to create a list where one comprehension is inside another. It’s like combining two loops in one line to build a complex list structure, often used for grids, tables, or even filtering and transforming nested data.
First, let’s recall how a nested loop works.
Example: Creating a 2D grid with numbers
Let’s start simple: Nested loops
First, let’s recall how a nested loop works.
Example: Creating a 2D grid with numbers
grid = [] for row in range(1, 4): # Outer loop for rows (1 to 3) row_list = [] # Start a new row for col in range(1, 4): # Inner loop for columns (1 to 3) row_list.append(col) # Add column numbers to the row grid.append(row_list) # Add the completed row to the grid print(grid) # Output: [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
Here’s what’s happening:
1. The outer loop creates each row.
2. The inner loop fills each row with column numbers.
3. Finally, all rows are combined into the grid.
Nested list comprehension
Now, we can write this in a nested list comprehension format:
grid = [[col for col in range(1, 4)] for row in range(1, 4)] print(grid) # Output: [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
What’s happening here?
1. Inner list comprehension:
- Creates a single row
2. Outer list comprehension:
- Repeats the inner list comprehension 3 times to create 3 rows.
Breaking it down
Here’s how it looks step by step:
1. For the first
2. For the second
3. This continues for all rows, resulting in a grid of lists.
Example 1: Multiplication table
Let’s generate a multiplication table (rows × columns):
table = [[row * col for col in range(1, 4)] for row in range(1, 4)] print(table)
Output:
[[1, 2, 3], [2, 4, 6], [3, 6, 9]]
- The inner comprehension computes
row * col for each column. - The outer comprehension repeats this for each row.
Example 2: Filtering with nested list comprehensions
You can also filter data inside a nested comprehension. Let’s keep only even numbers in a grid.
even_grid = [[col for col in range(1, 6) if col % 2 == 0] for row in range(1, 4)] print(even_grid)
Output:
[[2, 4], [2, 4], [2, 4]]
1. The inner comprehension generates only even numbers.
2. The outer comprehension repeats the filtered row for each
Key tips for beginners
1. Start with simple list comprehensions before attempting nested ones.
2. Always read from inside out when trying to understand them.
3. For complex cases, it’s okay to use regular nested loops for clarity.