0

so I have the following Python 3.9.9 code that creates two 4x3 boolean 2D-lists in two different ways which are initialized with all values set to False and changes the first element in the first list to True:

l1 = [[False for _ in range(3)] for _ in range(4)]
l2 = 4*[3*[False]]
print("l1 ([[False for _ in range(3)] for _ in range(4)]):")
print(l1)
print("l2 (4*[3*[False]]):")
print(l2)

l1[0][0] = True
l2[0][0] = True

print("l1 after [0][0] = True:")
print(l1)
print("l2 after [0][0] = True:")
print(l2)

and the output is this:

l1 ([[False for _ in range(3)] for _ in range(4)]):
[[False, False, False], [False, False, False], [False, False, False], [False, False, False]]
l2 (4*[3*[False]]):
[[False, False, False], [False, False, False], [False, False, False], [False, False, False]]
l1 after [0][0] = True:
[[True, False, False], [False, False, False], [False, False, False], [False, False, False]]
l2 after [0][0] = True:
[[True, False, False], [True, False, False], [True, False, False], [True, False, False]]

So the two 2D-lists look identical after creation, but why does the second 2D-list have the first element in other lists also changed when I only change the first element in the first list (l2[0][0])?

My assumption is that using the * with complex objects like lists makes the outer list store multiple pointers to the same object (in this case list)?

Wooow
  • 1

0 Answers0