Returns a shallow copy of a list.
list2 = list1.copy()
.copy() method has no parameters.
A Python list can be copied using the
= assignment operator:
list1 = [1, 2, 3, 4]list2 = list1print(list1) # Output: [1, 2, 3, 4]print(list2) # Output: [1, 2, 3, 4]
However, if you modify
list1 is also modified. This is because
list2 is actually pointing to the
If you want the original list unchanged when the new list is modified, you can use the
orders list using
Now if you change
orders stays the same.
If you are copying nested lists, shallow copy means if you modify any of the new nested list elements, changes are reflected in both the new and old lists as they point to the same reference. Whereas in deep copy, if you modify any of the new nested list elements, only the new list changes.
- christian.dinh2481 total contributions
- Anonymous contributorAnonymous contributor3077 total contributions