I’ve been struggling for hours trying to figure out why I kept getting extremely strange results in my application. Things just kept “turning on” when they certainly weren’t supposed to. I narrowed it down to a code segment very similar to the following:
test=[[False]*28]*24
print(test[5][7])
print(test[6][7])
test[5][7]=True
print(test[5][7])
print(test[6][7])
I only want to change the value of the 7th indice of the 5th indice in this particular case, however, various other indices are changes as well. Running this will get me:
False
False
True
True
While I would expect to get:
False
False
True
False
Does anybody understand why this is happening? Am I overlooking something? Does it have to do with how I’m initializing my list? I really just want a 24*28 list filled with bools = False.
The line
test=[[False]*28]*24creates 24 references to the same list of 28Falsevalues. You probably want something like:This forces the creation of 24 independent lists of
False.As a side note — you should consider
numpy.