lunasdejavu
lunasdejavu

Reputation: 89

appending elements to one of the lists of an array in python

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.

Upvotes: 1

Views: 178

Answers (1)

Saharsh
Saharsh

Reputation: 1098

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

Upvotes: 2

Related Questions