4

I can't seem to understand following behavior in python:

x = [0, [1,2,3,4,5],[6]]
y = list(x)
y[0] = 10
y[2][0] = 7
print x
print y

It Outputs:

[0, [1, 2, 3, 4, 5], [7]]
[10, [1, 2, 3, 4, 5], [7]]

Why is second index of x and y updated and only the first index of y?

1
  • 1
    ahh shallow copies and interning of ints Commented Feb 2, 2016 at 16:49

2 Answers 2

6

This happens because list(x) creates a shallow copy of the list x. Some of the elements in x are lists themselves. No copies are created for them; they are instead passed as references. In this way x and y end up having a reference to the same list as an element.

If you want to create a deep copy of x (i.e. to also copy the sublists) use:

import copy
y = copy.deepcopy(x)
Sign up to request clarification or add additional context in comments.

Comments

0

In Python,sequence are divided into mutable sequence,which can be changed after they are created, and immutable sequence.For immutable sequences(string,Unicode,Tuples),Python make a copy for them.For mutable sequences(Lists,Byte Arrays), Python make a reference for them.

So if you change x ,y will also be changed as as they have a reference to the same list.

The standard type hierarchy

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.