2

i have this piece of code

x=3
a=x*[x*[0]]
for i in range(0,x):
   for j in range(0,x):
       dt=int(input("insert data: "))
       a[i][j]=dt
       print(a)

and it's supposed to just add the numbers when is asked, but for some reason it fills the numbers in all the rows

CaptainJAL
  • 23
  • 3

1 Answers1

3

you just created 3 rows with the same reference with a=x*[x*[0]]. x*[0] is built once, and propagated on all rows by the outer multiply operator.

Changing a row changes all the rows. Note that it can be useful (but not there obviously)

Do that instead (using a list comprehension):

a=[x*[0] for _ in range(x)]

so references of each row are separated

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219