1

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.

asked May 4, 2018 at 6:27
2
  • 2
    Because A[1] and B[1] are pointing to the same address when you use [:] Commented May 4, 2018 at 6:37
  • 1
    If you want a deepcopy you should use copy.deepcopy. The [:] only makes a shallow copy. Commented May 4, 2018 at 6:51

1 Answer 1

1

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.

answered May 4, 2018 at 6:43
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.