-1

Im trying to make an 9x9 array using nested lists and when I set am trying to set a single value for some reason it is setting that value in every row of that array. It starts with a list like this

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

I did something like list[2][3]=1 and the list changed to

[[0,0,0,1,0],
 [0,0,0,1,0],
 [0,0,0,1,0],
 [0,0,0,1,0],
 [0,0,0,1,0]]

I can't figure out what I did wrong. My code is

def resetGrids():
    gridHidden=[]
    gridShown=[]
    gridpart=[]
    for i in range(9):
        gridpart.append(0)
    for i in range(9):
        gridHidden.append(gridpart)
        gridShown.append(gridpart)
    for i in range(10):
        searching=True
        while searching:
            checkX=random.randint(0,8)
            checkY=random.randint(0,8)
            print(checkX, checkY)
            if gridHidden[checkY][checkX]!=10:
                print(gridHidden[checkY][checkX])
                gridHidden[checkY][checkX]=10
                print("a")
                #for a in range(-1,2):
                #    if checkY+a>=0 and checkY+a<=8:
                #        for b in range(-1,2):
                #            if checkX+b>=0 and checkX+b<=8:
                #                if gridHidden[checkY+a][checkX+b]!=10:
                #                    gridHidden[checkY+a][checkX+b]+=1
                searching=False
                print("B")
            print(gridHidden)
        print("c")
    print("d")
Destroyer
  • 1
  • 2
  • Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) You can't append the same list `b` to `a` 9 times and then be surprised that changing one `b` changes all `b`. – Pranav Hosangadi Oct 07 '20 at 16:22

1 Answers1

1

try to set as the inner lists copy() of the actual list, I guess that it happend because you actually pass a reference to the list. replace to this lines:

gridHidden.append(gridpart.copy())
gridShown.append(gridpart.copy())

when I tried this, and added this part:

print(gridHidden)
gridHidden[1][2] = 3
print(gridHidden)

I got this:

[[0, 10, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 10, 0, 0, 10, 10, 0, 0, 10], [0, 0, 0, 0, 0, 0, 0, 10, 0], [0, 0, 0, 10, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 10, 0, 0, 0], [0, 0, 0, 0, 10, 0, 0, 0, 0], [0, 10, 0, 0, 0, 0, 0, 0, 0]]
[[0, 10, 0, 0, 0, 0, 0, 0, 0], [0, 0, 3, 0, 0, 0, 0, 0, 0], [0, 10, 0, 0, 10, 10, 0, 0, 10], [0, 0, 0, 0, 0, 0, 0, 10, 0], [0, 0, 0, 10, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 10, 0, 0, 0], [0, 0, 0, 0, 10, 0, 0, 0, 0], [0, 10, 0, 0, 0, 0, 0, 0, 0]]
Yossi Levi
  • 1,258
  • 1
  • 4
  • 7