0

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.

  • "I'm assuming it has to do with the fact that arrays are passed by reference in Python." no, that is incorrect. Python arrays (actually, the correct term is list) are not passed by reference. Pass by reference is not ever an evaluation strategy used by Python, and the evaluation strategy **doesn't depend on the type of object involved**, and there is only a single evaluation strategy used (which is neither call by reference nor call by value) – juanpa.arrivillaga Aug 08 '23 at 08:47
  • anyway, as you'll read in the linked duplicate, `result = [[0]*3]` is equivalent to `_temp = [0]; result = [_temp, _temp, _temp]` i.e., the *same object* is added to the list multiple times. The `*` operator implementation does not implicitly copy the objects (implicit copies essentially never occur in built-in Python data structures or the standard library, outside of special cases where it can't work any other way). On the other hand, for the list comprehension, a new inner list is created on each iteration. – juanpa.arrivillaga Aug 08 '23 at 08:55

0 Answers0