Can someone please explain,why below shallow copy code eg are not working as expected?Note:In the case of shallow copy, a reference of an object is copied into another object. means any changes made to a copy of an object do reflect in the original object

import copy

s = [1, 2, 2, 4, 6, 7, 1]
shallow = copy.copy(s)
s[4] = 2
print(s) # Output: [1, 2, 2, 4, 2, 7, 1]
print(shallow) # Output: [1, 2, 2, 4, 6, 7, 1]

What did you expect? That shallow was going to be the same list as s?

When you do a shallow copy, you make a copy of that object, but references within that object are not copied. You end up with a new list with references to the same elements that were in the original list.
The elements of s were not copied, but integers are immutable so it doesn’t matter if you copy them anyway.

When you change s[4] = 2 you’re changing the 5th element in that list, but the other list is unchanged, as you can see.

It would be a different situation if s contained a nested list:

s = [1, 2, 2, 4, [6], 7, 1]
shallow = copy.copy(s)
s[4][0] = 2
print(s) # Output: [1, 2, 2, 4, [2], 7, 1]
print(shallow) # Output: [1, 2, 2, 4, [2], 7, 1]

Thank you for providing a clear and accurate explanation of how shallow copying works in Python.
Have a great day! :smiling_face:

1 Like

Hi Pragnya and welcome.

To be clear: the way to get the result you expected is… just ordinary assignment, shallow = s. The purpose of copying (whether shallow or deep) is to make a new object. The idea of shallow copy is that the elements are assigned, instead of also being copied.

A deep copy will try to copy elements of the list, and elements of any of those elements if they are also lists, etc. It can also handle more complex types and more complex data structures, including if they contain cycles. It’s quite complex, which is why there is a copy standard library module that provides deepcopy. However, in modern Python we do not really need copy.copy most of the time. For example, the list type now has its own copy method that makes a shallow copy.

Here are some more links you may find useful to get a really full understanding of Python’s assignment and copying model:

In the future, I also hope to have corresponding information available on Codidact.