python-3.xobjectcopydeep-copyshallow-copy

Copying in python


Can someone explain why this is happening?

>>> A = [1,[2,3],4] 
>>> B = A[:]
>>> B[0] = 'x'
>>> B
['x',[2,3],4]
>>>A
[1,[2,3],4]
>>> B[1][0] = 'y'
>>> B
['x',['y',3],4]
>>> A
[1,['y',3],4]

At the end when we've asked to return A, we should get [1,[2,3],4] as answer, right? as we have created separate copy for B.


Solution

  • Lists are references by default in python. When you assigned B = A[:] you were trying to create a copy of A. It works as you expected for normal values. But second element of A is in turn another List(that is [2,3]), which in turn is another reference.

    In other words think of it this way B = A[:] is like saying

    B = []
    B[0]=A[0] # here A[0] = 1
    B[1]=A[1] # here A[1] is a reference to [2,3]
    ......
    

    So in effect the second element of both B and A are a reference to the same List.