Fundamentals 4 min read

Understanding Python Assignment, Shallow Copy, and Deep Copy

This article explains Python's variable storage model and demonstrates how assignment, shallow copy, and deep copy affect object references and memory addresses for immutable and mutable types, using string and list examples to illustrate the differences.

360 Quality & Efficiency
360 Quality & Efficiency
360 Quality & Efficiency
Understanding Python Assignment, Shallow Copy, and Deep Copy

Before discussing shallow and deep copies in Python, it is useful to understand how variables are stored in memory: every variable is an object and assignment copies only the reference (the memory address) rather than the object itself.

For immutable types such as numbers and strings, assigning a new value creates a new object, while for mutable containers (lists, tuples, dictionaries) the reference remains the same. The article demonstrates this difference with examples that append a suffix to strings and to list elements.

Assignment: the same memory address is shown for both strings and list elements after assignment, but when a suffix is added, the string’s address changes while the list’s element address does not, illustrating that the list holds references to the same objects.

Shallow copy: only the outer container is duplicated; inner objects are still referenced. After a shallow copy, the list’s outer address changes, but the strings inside retain their original addresses, showing that only the first level is copied.

Deep copy: the container and all nested objects are recursively duplicated. The deep‑copy example shows that both the outer list and its inner strings receive new addresses, while immutable objects like numbers and strings at the deepest level keep their original addresses.

In summary, assignment copies references, shallow copy duplicates the top‑level container, and deep copy duplicates all nested objects, affecting memory usage and mutability behavior in Python.

pythonmemorydeep copyImmutableAssignmentshallow copyMutable
360 Quality & Efficiency
Written by

360 Quality & Efficiency

360 Quality & Efficiency focuses on seamlessly integrating quality and efficiency in R&D, sharing 360’s internal best practices with industry peers to foster collaboration among Chinese enterprises and drive greater efficiency value.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.