0

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

Community
  • 1
  • 1
user2461671
  • 41
  • 1
  • 5

1 Answers1

3

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.

Warwick Masson
  • 883
  • 7
  • 17
  • Any recommendations for the best way to make such a structure without typing it? I think numpy may be the best option, but I haven't figured that out yet. – user2461671 Jun 07 '13 at 03:33