Copy or Alias
A grid is a list of rows, and each row is a list of numbers. Write copy_grid(grid) that returns a new grid with the same values, such that changing the copy never changes the original.
Every row of the copy must be its own list, even when the original uses the same list object for several rows.
Understand the problem
Predict how Python shares objects.
What does this print?
row = [0, 0]
grid = [row, row]
grid[0][0] = 9
print(grid)
[[9, 0], [0, 0]][[9, 0], [9, 0]][[0, 0], [0, 0]]
grid holds two references to the same list. Changing grid[0][0] changes that one list, and both rows show it. The same trap appears with [[0] * 2] * 2.
a = [[1], [2]] and b = a[:]. Then b[0].append(5). What is a?
[[1], [2]][[1, 5], [2]]
a[:] is a shallow copy: a new outer list whose items are the same inner lists. b[0] and a[0] are one list, so the change shows in both.
Write the solution
Think about what must be copied and how deep.
def copy_grid(grid):
# Write your code here.
pass
Hint 1: a question to ask yourself
How many levels of lists need to be new objects?
Hint 2: the shape of the answer
A new outer list, with a new list for every row. A comprehension that copies each row (row[:] or list(row)) does it.
Reflect
Solution
def copy_grid(grid):
return [list(row) for row in grid]
What this tests: references versus values, shallow versus deep copies, and list comprehensions.
Why not copy.deepcopy? It copies everything, but it also preserves sharing: if the original uses the same row twice, the deep copy uses one new row twice. Here the task says every row must be separate, so deepcopy gives the wrong answer for such grids. Knowing what deepcopy actually promises is the point of this problem.
Why not grid[:] or list(grid)? They copy only the outer list. The rows stay shared with the original.
Cost: O(rows x columns) time and space.
What an interviewer might ask next: For a grid of numbers list(row) is enough. What would you change for a grid whose cells are themselves lists?
VISIBLE = 3
CASES = [
('g = [[1, 2], [3, 4]]\nc = copy_grid(g)\nc[0][0] = 99\nresult = g', [[1, 2], [3, 4]], 'changing the copy leaves the original alone'),
('g = [[1, 2], [3, 4]]\nc = copy_grid(g)\nresult = (c == g, c is g)', (True, False), 'same values, different object'),
('g = [[1], [2]]\nc = copy_grid(g)\nresult = c[0] is g[0]', False, 'rows are new lists'),
('g = []\nc = copy_grid(g)\nresult = (c, c is g)', ([], False), 'an empty grid'),
('row = [0, 0]\ng = [row, row]\nc = copy_grid(g)\nc[0][0] = 1\nresult = c', [[1, 0], [0, 0]], 'a row used twice in the original'),
('g = [[1, 2]]\nc = copy_grid(g)\ng[0].append(3)\nresult = c', [[1, 2]], 'changing the original leaves the copy alone'),
]