+ 3
Why the List is [[7],[7],[7]],not[[7],[0],[0]]?
this is a code questions which I originally meet when I challenge other in sololearn(I add some code wanting to figure out the list)I wonder that why the List is [[7],[7],[7]],not[[7],[0],[0]]?thanks~ arr=[[]]*3 print(arr)#output is [[],[],[]] arr[0].append(7) print (arr)#output is [[7],[7],[7]] #why not [[7]],[],[]] try: print(arr[1][0]) except IndexError: print("0")
2 Réponses
+ 2
When you create a two dimensional array in python like the following
arr=[[]]*3
All the three rows refer to single row in memory
Row 0-->[ X, X, X]
Row 1 --|
Row 2--|
So if we assign a value to any row, it will be affected in all other rows.
To avoid this , you can create a matrix like the following.
columns = 3
rows = 3
mat = [ [0 for i in range(columns)] for j in range(rows)]
mat[0][0] = 1 # Will not affect other rows
print(mat([1][0]) # Prints Zero
0
thank you very much!!!