When confused about the Python Data Model, you can use ‘memory_graph’:
to draw a graph of your data and easily see what data is shared.
import memory_graph # see install instructions at link above
a = [[1,1],[1,1]]
b = a.copy()
b[0][0] = -1
print(a)
print(b)
memory_graph.d() # draw graph
[[-1, 1], [1, 1]]
[[-1, 1], [1, 1]]
If you instead make a deep copy then ‘a’ and ‘b’ are not shared, and thus you can change one without changing the other:
import memory_graph
import copy
a = [[1,1],[1,1]]
b = copy.deepcopy(a) # <-------- deep copy
b[0][0] = -1
print(a)
print(b)
memory_graph.d()
[[1, 1], [1, 1]]
[[-1, 1], [1, 1]]
(I’m sorry I’m prohibited from adding a second image to this post to show the difference)
See the link above for an explanation of the Python Data Model and shallow/deep copy.
Full disclosure: I am the developer of memory_graph.