Python Basics: Understanding Shallow and Deep Copies
Before changing a list or dictionary, you may want a separate version. Python’s standard-library copy module helps control which parts become independent.
Use Python 3.12 or newer in Bash on Linux. Each example runs independently and changes only in-memory data.
Notice when two names share one object
Save as demo_copy_1.py:
shopping_list = ["apples", "bread"]
another_name = shopping_list
another_name.append("milk")
print("Original:", shopping_list)
print("Same object:", another_name is shopping_list)Run it from the directory where you saved it:
python3 demo_copy_1.pyOutput:
Original: ['apples', 'bread', 'milk']
Same object: TrueAssignment creates another reference to the same list, often called an alias. Appending through either name changes that one object. Use is to check object identity; == compares values instead.
Make a shallow copy
Save as demo_copy_2.py:
import copy
original = {"title": "Shopping", "items": ["apples"]}
edited = copy.copy(original)
edited["title"] = "Weekend shopping"
edited["items"].append("bread")
print("Original:", original)
print("Edited:", edited)
print("Same dictionary:", original is edited)
print("Same item list:", original["items"] is edited["items"])Run it from the directory where you saved it:
python3 demo_copy_2.pyOutput:
Original: {'title': 'Shopping', 'items': ['apples', 'bread']}
Edited: {'title': 'Weekend shopping', 'items': ['apples', 'bread']}
Same dictionary: False
Same item list: TrueA shallow copy makes a new outer container while retaining references to its contents. Replacing edited["title"] affects only that dictionary. Appending to its nested list affects both. For ordinary lists and dictionaries, their .copy() methods also make shallow copies.
Copy nested data independently
Save as demo_copy_3.py:
import copy
template = {"title": "Shopping", "items": ["apples"]}
weekend = copy.deepcopy(template)
weekend["items"].append("bread")
print("Template:", template["items"])
print("Weekend:", weekend["items"])
print("Same item list:", template["items"] is weekend["items"])Run it from the directory where you saved it:
python3 demo_copy_3.pyOutput:
Template: ['apples']
Weekend: ['apples', 'bread']
Same item list: Falsedeepcopy() recursively copies nested data, making it useful for editing a template. It keeps track of objects already copied, so repeated references inside a copy can still share one copied object.
Choose based on the changes you need: assignment for sharing, a shallow copy for replacing outer entries, and a deep copy for independent nested changes. Deep copying can cost more time and memory. It is not a universal snapshot: open files and sockets are unsupported, and custom classes can define their copying behavior.
References
Acknowledgements
This post was created with assistance from AI.