Deep Copy vs Shallow Copy

Hard ⏱ 18 min 31% acceptance ★★★★★ 4.9
Write a function independent_copy(matrix) that takes a list of lists matrix (a 2D grid) and returns a fully independent copy: mutating any inner list of the copy must never affect matrix. A naive list(matrix) or slicing only copies the outer list, leaving inner lists shared — your solution must avoid that trap without using the copy module.

Examples

Example 1
Input
independent_copy([[1, 2], [3, 4]])
Output
[[1, 2], [3, 4]]
Explanation

Same values, but every inner list is a brand-new object.

Constraints

  • `matrix` is a list of lists of numbers (2 levels deep, no deeper nesting).
  • Do not import the `copy` module — build the independent structure manually.

Topics

Variables & Data Typescopying

Companies

MetaGoogle

Hints

Hint 1

A shallow `matrix[:]` copies the outer list but the inner lists remain shared.

Hint 2

A list comprehension that copies each row individually solves it: `[row[:] for row in matrix]`.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.