1

the version of python is 3.7.3 I want make an array of lists which none of the lengths of them are not equal. I tried

l= [[]] * 38
l[25].append['QQ']

it will show [['AA'], ['AA'], ['AA'], ['AA'], ['AA'], ['AA'], ['AA'], ['AA'], ['AA'], ['AA'], ['AA'], ['AA'], ['AA'], ['AA'], ['AA'], ['AA'], ['AA'], ['AA'], ['AA'], ['AA'], ['AA'], ['AA'], ['AA'], ['AA'], ['AA'], ['AA'], ['AA'], ['AA'], ['AA'], ['AA'], ['AA'], ['AA'], ['AA'], ['AA'], ['AA'], ['AA'], ['AA']]

it is the same for l= [['']] * 38

I want to know why I can't use the append function.

lunasdejavu
  • 89
  • 1
  • 8
  • 1
    I literally faced this problem few days ago. The `*` operator for 2D or more dimension list is problematic. I would recommend looping through the outer list to make a 2-D list – Saharsh Oct 14 '19 at 06:13
  • 1
    These questions may provide a hint: https://stackoverflow.com/q/8822728/1630906, https://stackoverflow.com/q/1959744/1630906 – ekuusela Oct 14 '19 at 06:16

1 Answers1

2

Don't use * operator on list unless you want to treat each element as same. What this does is it allocates one memory space for one element and just replicate all the elements with the same space. So any changes done on any of the element will reflect changes in all of them.

Only option here is to use a loop.

>>> l = [[] for _ in range(38)]
>>> l[25].append('AA')
>>> l
[[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], ['AA'], [], [], [], [], [], [], [], [], [], [], [], []]

More about this problem here Changing an element in one list changes multiple lists

Saharsh
  • 1,056
  • 10
  • 26