1
s = [[0]*3]*3

i = 0 
while i < 3:
    j = 0
    while j < 3:
        print(s[i][j])
        s[i][j] += 1
        j += 1
    i += 1

The printed result of the above code really confused me, Why the second and third column of the array become [1,1,1] and [2,2,2] but not [0,0,0]?

MSeifert
  • 145,886
  • 38
  • 333
  • 352
Hongli Bu
  • 143
  • 2
  • 8

2 Answers2

1

Because when you create a list of lists using [[0]*3]*3, you're creating one list [0,0,0] three times, so you'll have [[0,0,0],[0,0,0],[0,0,0]], but all of the sub lists ([0,0,0]) are really refrencing the same list, since you just created one and multiplied it by 3 to create the others, so changing one list will make changes to the other lists.
To prevent this, create independent zero-ed lists using a list comprehension:

s = [[0]*3 for i in range(3)]

i = 0 
while i < 3:
    j = 0
    while j < 3:
        print(s[i][j])
        s[i][j] += 1
        j += 1
    i += 1
print(s) # just to see the final result

Which outputs:

0
0
0
0
0
0
0
0
0
[[1, 1, 1], [1, 1, 1], [1, 1, 1]]
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
0

because the way you create array is

s = [[0]*3]*3

which means all elements of s is the same list and once you change one of them, the rest of them will be changed too so if you want to get [[0,0,0],[1,1,1],[2,2,2]] as you said,try this:

import numpy as np
s = np.zeros((3,3))      #in this way you can get a 3*3 array
i = 0
while i < 3:
    j = 0
    while j < 3
        s[i][j] += i     #not plus 1,otherwise you will get [[1,1,1],[1,1,1],[1,1,1]]
        j += 1
    i += 1
Hejun
  • 366
  • 2
  • 9