0

The value of Index 1 changes in all rows in method1. How should I create an ar1 array correctly?

method1:

ar1= [[0] * 3] * 3

ar1[0][1]=5
print(ar1)

method2:

ar2=[
    [0,0,0],
    [0,0,0],
    [0,0,0],

]
ar2[0][1]=5
print(ar2)

output1:

[[0, 5, 0], [0, 5, 0], [0, 5, 0]]

output2:

[[0, 5, 0], [0, 0, 0], [0, 0, 0]]

1 Answers1

0
arr1 = [[0,0,0],[0,0,0],[0,0,0]]

(or)

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

(or)

arr1 = [[0 for _ in range(3)] for _ in range(3)]
Michael Back
  • 1,821
  • 1
  • 16
  • 17
  • This is actually a dup... but I haven’t seen all three places susccinctly in one place... the linked article is worth a read... it will explain why your first arr1 attempt was a problem. – Michael Back Apr 13 '19 at 03:35