0

I have a 3x3 zero matrix

a = [
[0,0,0],
[0,0,0],
[0,0,0]
]

Suppose I want to add 1 to the first element of the matrix. I use :

a[0][0] += 1

I thought it would add 1 to the a[0][0]th element and the matrix a would be :

a = [
[1,0,0],
[0,0,0],
[0,0,0]
]

But , in reality the matrix is now :

a = [
[1,0,0],
[1,0,0],
[1,0,0]
]

Why is 1 added to a[0][1] and a[0][2] also ?

Full snippet :

a = [[0] * 3] * 3 
a[0][0] += 1
print(a)

  • 3
    Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly). By doing `[...] * x` you create references to the same list object. You need to create independent lists for each row. Also, if you're going to work with multi-dimensional arrays, you might prefer using [`numpy`](https://numpy.org/) – Tomerikoo Aug 31 '20 at 08:36

1 Answers1

3

Have a look at this:

>>> a = [[0]*3]*3 
>>> a[0][0] = 1
>>> a
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
>>>
>>> b=[[0,0,0],[0,0,0],[0,0,0]]
>>> b[0][0] = 1
>>> b
[[1, 0, 0], [0, 0, 0], [0, 0, 0]]

So what happened here? Perhaps you misunderstand what multiplication [X]*3 does. The result is [X, X, X] where X is reference to the underlying object, not a (deep) copy. Which is what you want.

Your a list is a list with 3 elements, each one being literally the same list. While my b list is a list with 3 different lists, which happen to have the same values inside.


If you want to create such matrix with pure Python, then you can utilize this code:

def create_matrix(rows, columns, default_value=0):
    result = []
    for _ in range(rows):
        row = []
        for __ in range(columns):
            row.append(default_value)
        result.append(row)
    return result

a = create_matrix(3, 3)

I suggest looking at numpy (or similar) as well.

freakish
  • 54,167
  • 9
  • 132
  • 169