A report needs a revised schedule while keeping the original values.
What You Need to Understand
List mutation changes an existing object, so other references to that list observe the change. Creating a new list leaves the original intact unless you reassign its name.
When to Use It
A report needs a revised schedule while keeping the original values.
Step-by-Step Python Example
original = [1, 2]
alias = original
alias.append(3)
new_list = original + [4]
print(original)
print(new_list)
print(original is alias)
How the Example Works
Appending through alias changes original because both names reference one list. Concatenation makes a separate outer list.
Example Output
[1, 2, 3]
[1, 2, 3, 4]
True
['read', 'write'] ['read', 'write', 'review']
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
tasks = ["read", "write"]
revised = tasks.copy()
revised.append("review")
print(tasks, revised)
Important Behavior and Edge Cases
A shallow copy does not recursively copy nested lists. When independent nested data matters, consider copy.deepcopy().
Try It Yourself
Make a copy using items.copy() and change the copy without modifying the original.
Common Beginner Mistakes
- A shallow copy does not recursively copy nested lists. When independent nested data matters, consider
copy.deepcopy(). - Assuming every sequence operation modifies the original data or that a tuple makes nested mutable objects immutable.
Key Takeaways
- List mutation changes an existing object, so other references to that list observe the change.
- Appending through
aliaschangesoriginalbecause both names reference one list. - A shallow copy does not recursively copy nested lists.