Find the bug · #17 · Shared references Hard Python
Booking one seat books a whole column
In a cinema app, booking a single seat marks that seat taken in every row.
On this page
The report
In the cinema app, booking one seat marks the whole column as taken: every row shows that seat booked.
The code
Read it first: what should it do? Then click the line where you think the bug is.
def empty_hall(rows, cols):
"""A hall of seats; False means free."""
return [[False] * cols] * rows
def book(hall, row, col):
hall[row][col] = TrueRead it, then pick a line.
Does * rows make new rows, or repeat the same one?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
hall = empty_hall(3, 3)
book(hall, 0, 1)
for row in hall:
print("".join("X" if seat else "." for seat in row))It prints
.X. .X. .X.
It should print
.X. ... ...
Show the answer: the bug, the fix, and how you’d find it
The bug (line 3)
Line 3 builds the hall with [[False] * cols] * rows. The outer * rows doesn’t make new rows: it repeats a reference to the same row list. So there’s really one row, shown three times, and booking a seat in it shows up in every “row”. Build each row separately with a comprehension.
The fix
1def empty_hall(rows, cols):2 """A hall of seats; False means free."""3 return [[False] * cols] * rows3 return [[False] * cols for _ in range(rows)]4 5def book(hall, row, col):6 hall[row][col] = TrueHow you’d find it
- Reproduce: a 3 by 3 hall, book row 0, seat 1. Every row shows seat 1 taken.
bookchanges exactly one cell, so if three cells changed, the rows must be the same list.- Confirm it:
hall[0] is hall[1]isTrue.
The test that catches it
It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.
hall = empty_hall(2, 2)
book(hall, 1, 0)
assert hall == [[False, False], [True, False]]Where else this bites
- JavaScript’s
new Array(3).fill([])has the same problem. - Any 2D grid in a DSA problem: dynamic programming tables built this way give strange answers.