Mutability, Identity, and Copying
Unit ID: M03-U05 Estimated active time: 25-35 minutes
Two names can refer to one list
original_tags = ["python", "beginner"]
working_tags = original_tags
working_tags.append("data")
print(original_tags)
print(working_tags)
Both outputs include "data". Assignment did not create a new list. Both names refer to the same mutable object.
Test identity
print(original_tags is working_tags)
The result is True. The is operator checks object identity. Use == to compare values:
print(original_tags == working_tags)
Two separate lists can be equal without being the same object.
Make a shallow copy
original_tags = ["python", "beginner"]
working_tags = original_tags.copy()
working_tags.append("data")
print(original_tags)
print(working_tags)
print(original_tags is working_tags)
Now the original remains unchanged and identity is False.
List slicing also creates a shallow copy:
working_tags = original_tags[:]
Use .copy() when the intention is clearer.
Shallow copying has a boundary
original = {"title": "Python", "tags": ["beginner"]}
working = original.copy()
working["tags"].append("data")
The outer dictionaries are separate, but both still refer to the same nested list. The nested change appears in both records.
For this course, prefer rebuilding a small nested value explicitly when you need independence:
working = original.copy()
working["tags"] = original["tags"].copy()
working["tags"].append("data")
The standard library also provides deeper copying tools, but deep copying is not automatically correct for every data model.
Predict before running
scores = [6, 7]
review_scores = scores
review_scores[0] = 8
print(scores)
The output is [8, 7] because the names share one list.
Practice
Create an original course dictionary with a title and a list of tags. Make a working copy that can receive an extra tag without changing the original. Confirm value equality and identity before and after the change.
Takeaway
Assignment can create a shared reference to one mutable object. Copy at the level you intend to change, and verify both equality and identity when the distinction matters. Next, we will read nested structures made from lists and dictionaries.
