Search code examples
pythoniterationnested-lists

Setting a Value in a Nested Python List Automatically Iterates


I have a python list, created by model = [[[[0,0,0,0]]*4]*15]*5, which is a list that looks like this (without the brevity dots): model = [[[[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,0,0,0],...[0,0,0,0]]]]. The problem is that when I try to set one of the zeros to some other value using

def setLED(model,boardid,chipid,tankid,ledid,value): model[boardid][chipid][tankid][ledid]=value

every list of 4 zeros gets set the same. i.e. if I tried to use setLED(model,0,0,0,0,255), the first value in every list of 4 zeros would be 255. The intended result is that only the first list of 4 zeros, (i.e. model[0][0][0][0]), would be changed. I don't think there is a way to attach files, but if anyone needs it, I can post the full contents of the list.

Thanks in advance to anyone who can figure out why this is happening.

EDIT: This is a duplicate of Nested List Indices


Solution

  • When you create an array of arrays like this:

    [[0]]*n
    

    you are creating an array holding n references to the same array. You need to add new arrays in another manner. One way to do this would be to use list comprehensions, i.e.

    [[[ [0,0,0,0] for _ in range(4)] for _ in range(15)] for _ in range(5)]
    

    which does create new arrays instead of reusing references.