0

I'm new to python, and I'm having trouble with certain aspects of the language. Right now I'm trying to create a 3 dimensional table that can hold certain values.

table[x][y][z]

X and Y are both initialized to have the same number of elements, and z is initialized to be an empty list like so

table = [[[]]*length]*length

so that a table of length 3 would look like-

[[[],[],[]] , [[],[],[]] , [[],[],[]]]

At certain values of x, y I would like to be able to append a singular z list like this

table[0][2].append('S')

would cause the table to look like

[[[],[],['S']] , [[],[],[]] , [[],[],[]]]

but it's coming out like this

[[['S'],['S'],['S']] , [['S'],['S'],['S']] , [['S'],['S'],['S']]]

so that every z list is appended. Why is this happening and how can i fix it. I can work around this inefficiently but I don't want to.

  • See also http://stackoverflow.com/questions/14190513/append-to-a-sublist-appends-to-every-sublist/14190543#14190543 – Ry- Sep 30 '13 at 00:37

1 Answers1

1

The statement

table = [[[]]*length]*length

Just gives you references to the same 2 innermost lists over and over again.

Eric Urban
  • 3,671
  • 1
  • 18
  • 23
  • Sorry I'm terribly ill versed in python terminology. Are you saying that the same inner most list [] is being used for each value of x and y? And if so do you have any recommendations for how I would implement different inner most lists? a for loop where the inner loop is table[x][y] = []? –  Sep 30 '13 at 00:40
  • sorted thanks again though! –  Sep 30 '13 at 01:00