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 lessonThe 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
- Fix the Mutable DefaultIntermediate
- Predict the Output: Late BindingIntermediate
- Safe List FilteringIntermediate
- Predict the Output: Variable ScopeIntermediate
- Safe Exception HandlingIntermediate
- Build a Safe Defaults FunctionIntermediate
All Python exercises · 50 practice problems · Advanced Python quiz