Editor

Fix the Bug: Shallow Copy Surprise

Intermediate · Fix the bug · from 15 Python Pitfalls That Trip Up Even Experienced Developers

From the lesson: 15 Python Pitfalls That Trip Up Even Experienced Developers

Python is famous for being readable and beginner-friendly. But lurking beneath that clean syntax are several traps that catch even experienced developers. These aren't bugs in Python - they're features that behave differently than you'd expect.

Read the lesson

The code below tries to create an independent copy of a matrix, but modifying the copy also changes the original. Fix it so the original stays unchanged.

The output should show the original matrix unchanged after modifying the copy.

original = [[1, 2], [3, 4]]
copy_matrix = original.copy() # Bug: shallow copy!
copy_matrix[0][0] = 99
print(f'Original: {original}')
print(f'Copy: {copy_matrix}')

More Common Pitfalls exercises

All Python exercises · 50 practice problems · Advanced Python quiz