In Python, variables usually hold references to objects, not the objects themselves. Understanding references, shallow copy, and deep copy is essential when working with nested data.
References
If you write b = a, Python does not create a new copy. It makes b refer to the same object as a.
info = dict(name="Alice", skills=["Python", "C"])
info_ref = info
info_ref["skills"].append("Java")
print(info)Output:
{'name': 'Alice', 'skills': ['Python', 'C', 'Java']}Because info and info_ref point to the same dictionary, a change through one variable is visible through the other.
KNOWLEDGE QUIZ
Shallow Copy
A shallow copy copies the outer object, but not the nested child objects.
import copy
info = dict(name="Alice", skills=["Python", "C"])
info_copy = copy.copy(info)
info.pop("name")
info_copy["skills"].append("Java")
print(info)
print(info_copy)Output:
{'skills': ['Python', 'C', 'Java']}
{'name': 'Alice', 'skills': ['Python', 'C', 'Java']}The outer dictionaries are different, but the inner skills list is still shared.
Shallow copy: separate shells, shared child
A shallow copy creates a new outer dictionary, but both skills arrows still point to one list.
Both skills arrows converge on the same listKNOWLEDGE QUIZ
Deep Copy
A deep copy recursively copies the parent object and its child objects.
import copy
info = dict(name="Alice", skills=["Python", "C"])
info_copy = copy.deepcopy(info)
info.pop("name")
info_copy["skills"].append("Java")
print(info)
print(info_copy)Output:
{'skills': ['Python', 'C']}
{'name': 'Alice', 'skills': ['Python', 'C', 'Java']}After deep copy, the two skills lists are no longer the same object.
Deep copy: two independent rooms
Both outer dictionaries and both skills lists have different addresses. A nested edit stays in the copy.
The skills arrows point to two independent listsKNOWLEDGE QUIZ
Predict shallow-copy output
Without running the code, write both output lines, then verify. Explain why editing copy_data["scores"] appears on both sides while replacing copy_data["name"] affects only the copy.
Make independent student records
- Create a record with name, scores, and a nested contact dictionary.
- Use the appropriate copy operation to make a backup.
- Change the score and email in the backup.
- Print both records to prove the original is unchanged.