I was working on a simple python script and I encountered some unexpected behaviour that I narrowed down to being caused by the way in which I defined an array.
Example code:
l_1 = [[0]] * 10
l_2 = [[0] for _ in range(10)]
print(l_1)
print(l_2)
print()
l_1[2][0] += 1
l_2[2][0] += 1
print(l_1)
print(l_2)
Output:
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]]
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]]
[[1], [1], [1], [1], [1], [1], [1], [1], [1], [1]]
[[0], [0], [1], [0], [0], [0], [0], [0], [0], [0]]
Does anyone have an explanation for why Python is producing this output? I'm assuming it has to do with the fact that arrays are passed by reference in Python.