You want to edit a proposed shopping basket without immediately changing the original.
What You Need to Understand
list.copy() returns a shallow copy of a list. The new outer list has the same elements but is a different object.
When to Use It
You want to edit a proposed shopping basket without immediately changing the original.
Step-by-Step Python Example
basket = ["milk", "bread"]
proposed = basket.copy()
proposed.append("eggs")
print(basket)
print(proposed)
How the Example Works
The new entry appears only in proposed because the outer lists are independent.
Example Output
['milk', 'bread']
['milk', 'bread', 'eggs']
[[1, 9], [2]]
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
original = [[1], [2]]
shallow = original.copy()
original[0].append(9)
print(shallow)
Important Behavior and Edge Cases
For nested lists, copy() shares inner references. Use copy.deepcopy() only when independent nested data is necessary.
Try It Yourself
Copy a two-dimensional list and modify one inner list to observe shallow-copy behavior.
Common Beginner Mistakes
- For nested lists,
copy()shares inner references. Usecopy.deepcopy()only when independent nested data is necessary. - Using the wrong collection method for this operation without checking whether it mutates the object, returns a result, or raises on missing data.
Key Takeaways
list.copy()returns a shallow copy of a list.- The new entry appears only in
proposedbecause the outer lists are independent. - For nested lists,
copy()shares inner references.