0

I came across a piece of python code, requiring me to give the output. The code goes as follows:

a = [1, 2]
b = [a, 3]
c = b[:]
a[0] = 7
b[1] = 8
print c

I thought the output to be [[7, 2], 8] since i have the reference to the a in b, and consequently, c had the reference to b

But the output came out to be [[7, 2], 3]

What am I missing here?

6
  • 1
    Unlike c = b c = b[:] creates a (flat) copy of b as c. Changes in b are not reflected to c. Commented Dec 11, 2018 at 14:31
  • 1
    c = b[:] is a shallow copy Commented Dec 11, 2018 at 14:31
  • have a look to this:programiz.com/python-programming/shallow-deep-copy Commented Dec 11, 2018 at 14:45
  • @KlausD. if changes in b are not reflected in c , how come the changes in a are getting reflected in c ? Commented Dec 11, 2018 at 14:54
  • @ssein thanks, it really cleared a lot of concepts! Commented Dec 11, 2018 at 15:10

1 Answer 1

5

c had the reference to b

This is where you went wrong. c is initialized as a (shallow) copy of b.

If it were simply c = b (without the [:]) then you'd be correct.

Sign up to request clarification or add additional context in comments.

1 Comment

Had to clear a lot of concepts about shallow copy and deep copy. Thanks for the response. Marking it as accepted!

Your Answer

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.