2

I'm using the following code to input value to a nested list/matrix. But getting the identical row value assigned in the last row.

rows = int(input('Input the rows: '))
cols = int(input('Input the cols: '))
#rows, cols = (5, 5) 
arr1 = [[int(0)]*cols]*rows
print(arr1) 
for i in range(rows):
    for j in range(cols):
        arr1[i][j]= int(input('arr1[%d][%d]: '%(i,j)))
        print(arr1[i][j])
print(arr1) 

Let's

>>> Input the rows: 2
>>> Input the cols: 2

Then,

>>>rows
2
>>>cols
2

Afterwords,

arr1[0][0]: 22
arr1[0][1]: 33
arr1[1][0]: 44
arr1[1][1]: 55

Lastly, the issue found. Last row elements repeat through all the previous rows.

>>>print(arr1)
[[44, 55], [44, 55]]

It is also occurring for higher dimension matrices.

I don't want this to happen. Instead, I wish to get no repetition, like:

>>>print(arr1)
[[22, 33], [44, 55]]

Note : Using python 3

Community
  • 1
  • 1
KittoMi
  • 411
  • 5
  • 19
  • Does this answer your question? [Python: initialize multi-dimensional list](https://stackoverflow.com/questions/17636567/python-initialize-multi-dimensional-list) – Farshid Shekari Mar 15 '20 at 13:06

3 Answers3

2

You have a problem here:

arr1 = [[int(0)]*cols]*rows

Essentially, the * operator will create multiple references of the same object for mutable types. One way to fix this is to use comprehensions (also the int() call in int(0) is useless, so I'll just skip it), e.g.:

arr1 = [[0 for _ in range(cols)] for _ in range(rows)]

or:

arr1 = [([0] * cols) for _ in range(rows)]

The inner [0] * cols would work as you expect because 0 is immutable.

Idea O.
  • 420
  • 4
  • 10
1

This peculiar functioning is because Python uses shallow lists which we will try to understand. if you look here you can find your answer. Your problem is in creating your nested list.

arr1 = [[int(0)]*cols]*rows   <--- Here

And you can use this code instead of it:

arr1 = [[0 for i in range(cols)] for j in range(rows)] 
Farshid Shekari
  • 2,391
  • 4
  • 27
  • 47
0

The * in the code is the problem. It would create bigger references. You can make a blank list. arr1 = [] and append like this. arr1[i][j].append(int(input('arr1[%d][%d]: '%(i,j)))) Then the code would be easier to understand. and debuging is easier too.

jinwon2
  • 84
  • 11