0

I met a problem when I use python to process my data, I want a three dimensional array, the first dimension is fixed at 5, the elements in second dimension are added dynamically, it`s type is array, the third dimension is how many number in the array, it is fixed at 4. code snippet is as follows:

three_d_array = [[]] * 5 # [[], [], [], [], []]
three_d_array[0] = [1,2,3,4] # [[1,2,3,4],[],[],[],[]]
three_d_array = [[]] * 5 # [[], [], [], [], []]
three_d_array[0].append([1,2,3,4]) # [[[1, 2, 3, 4]], [[1, 2, 3, 4]], [[1, 2, 3, 4]], [[1, 2, 3, 4]], [[1, 2, 3, 4]]]

I know *5 will generate one copy but five references, but why '=' can break this relationship? '=' must assign new memory address for this array, I wonder it assign five copies for three_d_array[1:5] or just one for three_d_array[0]?

Dongwei Wang
  • 475
  • 5
  • 14
  • 1
    Basically the problem is in the first case, your inner elements are actually the same empty array, append then operates on that array. – pvg Jan 11 '16 at 02:44
  • what I understand is inner elements will added dynamically, it`s length is not fixed, however out layer length is fixed at 5, because I initialized it with *5, python does not allocate five same memory space, just one, all the elements are reference, that is why if I append() elements, all of them changed – Dongwei Wang Jan 12 '16 at 15:58
  • That's not true, all lists in python are dynamic and all python objects are heap allocated (if you want to look at it in C++ terms). The only thing different that in the *5 case, the inner element is a reference to the _same_ list. That's it. – pvg Jan 12 '16 at 16:19

0 Answers0