ProgrammingHardProduct-company MCQ pattern

What is printed?

What is printed?
grid = [[0, 0]] * 2
copy1 = list(grid)
copy2 = [row[:] for row in grid]
grid[0][0] = 1
grid[1] = [5, 5]
print(copy1, copy2, grid)
  1. A. [[0, 0], [0, 0]] [[0, 0], [0, 0]] [[1, 0], [5, 5]]
  2. B. [[1, 0], [0, 0]] [[0, 0], [0, 0]] [[1, 0], [5, 5]]
  3. C. [[1, 0], [5, 5]] [[0, 0], [0, 0]] [[1, 0], [5, 5]]
  4. D. [[1, 0], [1, 0]] [[0, 0], [0, 0]] [[1, 0], [5, 5]]

Correct answer: D. [[1, 0], [1, 0]] [[0, 0], [0, 0]] [[1, 0], [5, 5]]

[[0, 0]] * 2 holds the SAME inner list twice. list(grid) is a shallow copy: a new outer list pointing at that same inner list, so grid[0][0] = 1 shows up in both rows of copy1. copy2 copied each row, so it is unaffected. grid[1] = [5, 5] rebinds a slot of grid only; copy1's slots still point at the shared row.

More Python Programming questions

Exams that ask this topic