# How may I copy a list of list without reference?

I can copy a list without reference

a = [3,4,5]
b = a.copy()
b[0] = -1
print(a)
print(b)
>>[3, 4, 5]
>>[-1, 4, 5]

but why can’t I do the same for a list of list? What should I do?

a = [[1,1],[1,1]]
b = a.copy()
b[0][0] = -1
print(a)
print(b)
>>[[-1, 1], [1, 1]]
>>[[-1, 1], [1, 1]]

The terms in question are: “shallow-copy” and “deep-copy”.

Web.Refs:

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.

1 Like