6.2 copy and References
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.
python
info = dict(name="Alice", skills=["Python", "C"])
info_ref = info
info_ref["skills"].append("Java")
print(info)Output:
text
{'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.
Loading concept check...
Shallow Copy
A shallow copy copies the outer object, but not the nested child objects.
python
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:
text
{'skills': ['Python', 'C', 'Java']}
{'name': 'Alice', 'skills': ['Python', 'C', 'Java']}The outer dictionaries are different, but the inner skills list is still shared.
Loading interactive lab...
Deep Copy
A deep copy recursively copies the parent object and its child objects.
python
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:
text
{'skills': ['Python', 'C']}
{'name': 'Alice', 'skills': ['Python', 'C', 'Java']}After deep copy, the two skills lists are no longer the same object.
Loading concept check...
Loading practice...