What is the difference between shallow copy and deep copy?medium

Type
conceptual
Topic
shallow-copy-deep-copy
Frequency
common
Tags
shallow copy, deep copy, identity, equality, memory
Answer

A shallow copy duplicates the outer container but shares references to inner objects. A deep copy recursively duplicates everything. == checks value equality via __eq__; is checks identity — whether two names point to the same object in memory.

Explanation

The classic shallow copy bug: modifying a nested list in a shallow copy also modifies the original because both point to the same inner list. Deep copy via copy.deepcopy() creates fully independent objects at every nesting level. Python interns small integers (-5 to 256) and short strings, so a is b may be True for small numbers — but never rely on this, as it is a CPython implementation detail. Assignment (b = a) creates another reference to the same object, not a copy.

Follow-upWhen can deep copy be risky or expensive?
Follow-upWhen would you use is instead of ==?
Follow-upWhat does Python's integer interning mean in practice?