Legends ofPythos
Claim your name
Working with Data

Nested comprehensions and del

Lesson 9 of 14

Watch the lesson1:15 ยท with Torsten
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]
Reading order matters: left to right, top to bottom.

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]]
A comprehension inside a comprehension.
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}
Removing items by index or key.

Your turn

0 of 3 solved

Exercise 1

+30 XP
seating is a list of tables, each a list of guest names. Build guests, every name in order table by table, with one comprehension that has two for clauses. Then build initials, the first letter of every name, as a flat list in the same way. guests starts ['Ada', 'Brian', 'Cleo', ...].
seating = [['Ada', 'Brian'], ['Cleo'], ['Dan', 'Eve', 'Fay']]


guests = []    # one comprehension, two for clauses
initials = []  # the first letter of every name

Run your code to check it against the tests.

Exercise 2

+30 XP
scores holds three players' scores over four rounds, one row per player. Build by_round, the grid turned on its side (one row per round, holding each player's score for that round), with a comprehension inside a comprehension. Then build round_totals, the total of each round. by_round[0] is [3, 4, 7].
scores = [
    [3, 5, 2, 8],
    [4, 4, 6, 1],
    [7, 0, 3, 5],
]


by_round = []
round_totals = []

Run your code to check it against the tests.

Exercise 3

+30 XP
Tidy the camp stores with del. Delete the first item of packs, then its last item (index -1), then the 'lamp oil' key from stock, and finally the variable spare itself. Then print packs, and then sorted(stock).
packs = ['rope', 'tent', 'stove', 'map', 'torch']
stock = {'bread': 4, 'lamp oil': 1, 'salt': 2}
spare = 'old boots'


# 1. delete the first pack
# 2. delete the last pack
# 3. delete the 'lamp oil' key
# 4. delete the name spare
# 5. print packs, then sorted(stock)

Run your code to check it against the tests.