Reputation: 1900
I was trying this out
>>> x = [[1, 2, 3], 10.5]
>>> z = list(x)
>>> z[1] = 10.6
>>> z
[[1, 2, 3], 10.6]
>>> x
[[1, 2, 3], 10.5]
>>> z[0][2] = 5
>>> z
[[1, 2, 5], 10.6]
>>> x
[[1, 2, 5], 10.5]
Why the change is being reflected in x[0][2] ? and similarly not in x[1]???
Upvotes: 1
Views: 44
Reputation: 15854
The list(x)
created a new top-level list thus changing its top-level values - like 10.5
- won't propagate to x
. On the other hand, the inner list is a reference thus changes to it are shared amongst all containers containing it because they all contain the very same object. If you would like a separate copy of x
, use copy.deepcopy.
Upvotes: 2