Understanding Deep Vs Shallow Copy In Python 2.x
I was looking online and I came across these 3 segments of code. The question is to predict the output and explain why. Example 1: x = 42 y = x x = x + 1 print x print y Output E
Solution 1:
Ok so we can dissect this a bit more:
>>> x = ['foo', [1,2,3], 10.4]
>>> y = list(x) # or x[:]
>>> z=x
>>> id(x)
4354889544
>>> id(y)
4354890184
>>> id(z)
4354889544
>>> y[0] = 'fooooooo'
>>> y[1][0] = 4
>>> y
['fooooooo', [4, 2, 3], 10.4]
>>> x
['foo', [4, 2, 3], 10.4]
>>> id(x[1])
4354889672
>>> id(y[1])
4354889672
See it now? When you use the function List()
it is creating a new object in a new memory location... but to save space python will keep the same pointer to the mutable internal objects, like the list. This article can explain more what is mutable and what is not.
Post a Comment for "Understanding Deep Vs Shallow Copy In Python 2.x"