amyotun - 1 year ago 196
Python Question

Insert value into the element of 2D array

Supposed I created the 2D array of 3x4 with zeros initialization.
Then, I want to add 100 into arr[0][1] and I expect that 100 is added Only into arr[0][1] cell. Refer to Case 1 and Case 2:

From Case 1:
what I saw is that 100 is added into every row with column 1 of arr. It is not what i expected.

From Case 2
The result is what i have expected. Can anyone help me explain?

``````Case 1:
>>> arr = [[0]*4]*3
>>> arr
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
>>> len(arr)
3
>>> len(arr[0])
4
>>> type(arr)
<class 'list'>

>>> arr[0] [1] = 100
>>> arr
[[0, 100, 0, 0], [0, 100, 0, 0], [0, 100, 0, 0]]

Case 2:
>>> arr = [[0]*4 for _ in range(3)]
>>> arr
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

>>> type(arr)
<class 'list'>

>>> arr[0] [1] = 100

>>> arr
[[0, 100, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
``````

`[0]*4` creates a list of references to the same object 0. Since integers are immutable, that's OK; changing one element replaces it with a new object. However, `[[0]*4]*3]` creates a list with 3 references to the same, mutable list object that contains 4 references to 0. Changing an element of one list, as you've seen, shows up as a change in all 3 references.
In the list comprehension, a new list `[0]*4` is created for each value of `_`, rather than simply storing a new reference to the same list.