View original source
article

Python Shallow Copies Share Nested Mutables

list.copy() creates shallow copies that share nested mutable objects, so modifying them alters originals—use deepcopy for safe independent copies.

Shallow Copies Fail on Nested Mutables

Python's list.copy() or slicing (e.g., my_list:) produces shallow copies: top-level elements are duplicated, but nested mutable objects like lists or dicts are shared references. Modifying a nested item in the copy changes the original, causing silent data corruption during experiments.

Example pitfall: If original_list = [[1,2], 3,4], then copy_list = original_list.copy(); copy_list[0]0 = 99 also sets original_list[0]0 to 99.

Deepcopy Ensures Independence

Use copy.deepcopy() to recursively copy all nested structures, creating fully independent data. This prevents betrayal in iterative workflows where you transform data (remove items, add values) while preserving raw originals for validation and comparison.

Rule for data scientists/engineers: Never modify raw data—always deepcopy first to safely iterate, validate transformations, and compare original vs. modified without data loss.

Trade-off: Deepcopy is slower and memory-intensive for large/deep structures, so use shallow copy when no nested mutables exist.

Summarized by x-ai/grok-4.1-fast via openrouter

3622 input / 781 output tokens in 6701ms

© 2026 Edge