A task list is copied for a second employee.
What You Need to Understand
Assignment copies a reference, not a list. Slicing with [:] and list.copy() create a new outer list but share nested objects. Understanding the difference prevents changes from appearing in unexpected places.
When to Use It
A task list is copied for a second employee.
Step-by-Step Python Example
tasks = ["read", "write"]
alias = tasks
copy_of_tasks = tasks.copy()
alias.append("test")
print(tasks)
print(copy_of_tasks)
print(tasks is alias, tasks is copy_of_tasks)
How the Example Works
The alias points at the same list and sees the appended value; the separate copied list does not.
Example Output
['read', 'write', 'test']
['read', 'write']
True False
True False
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
source = [1, 2]
copy_by_slice = source[:]
print(source == copy_by_slice, source is copy_by_slice)
Important Behavior and Edge Cases
This is only a shallow copy. Copying a list of lists preserves references to its inner lists.
Try It Yourself
Try slice copying and compare object identity with is.
Common Beginner Mistakes
- This is only a shallow copy. Copying a list of lists preserves references to its inner lists.
- Overlooking how an iterable is consumed, how element positions are chosen, or whether a function creates a new list.
Key Takeaways
- Assignment copies a reference, not a list.
- The alias points at the same list and sees the appended value; the separate copied list does not.
- This is only a shallow copy.