You already know how to write a single list comprehension. Now you can chain multiple
for clauses together. This is called nesting.Flattening with nested comprehensions
grid = [
[1, 2],
[3, 4]
]
# This reads like nested loops:
# for row in grid:
# for cell in row:
# ...cell...
cells = [cell for row in grid for cell in row]
print(cells) # [1, 2, 3, 4]Building and transposing grids
# Build a 3x2 grid
width = 2
height = 3
generated_grid = [[i * width + j for j in range(width)] for i in range(height)]
print(generated_grid) # [[0, 1], [2, 3], [4, 5]]
# Transpose a grid (swap rows and columns)
grid = [[1, 2], [3, 4]]
cols = len(grid[0]) if grid else 0
transposed = [[row[i] for row in grid] for i in range(cols)]
print(transposed) # [[1,3],[2,4]]When to stop. If you need three or more nested loops, the comprehension becomes hard to read. A standard
for loop is often better for complex logic.The del statement
# 1. Delete a list item by index
items = ['a', 'b', 'c']
del items[0]
print(items) # ['b', 'c']
# 2. Delete the last item with a negative index
scores = [85, 90, 76, 100]
del scores[-1]
print(scores) # [85, 90, 76]
# 3. Delete a dictionary key
prices = {'tea': 2.0, 'coffee': 4.0}
del prices['tea']
print(prices) # {'coffee': 4.0}