Medium: Interview Core · Problem 24 of 82

Copy or Alias

MediumPython BasicsPython

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)
  1. [[9, 0], [0, 0]]
  2. [[9, 0], [9, 0]]
  3. [[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. [[1], [2]]
  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?