Mrugesh
Mrugesh

Reputation: 4517

Appending element into the list of list overrides the entire list

Code is as shown below :

s = [[]] *4
s[0].append(1)

print(s)

it gives me output :

[[1],[1],[1],[1]]

but i want output like this :

[[1],[],[],[],[]]

How can i achieve that?

Upvotes: 1

Views: 49

Answers (2)

altunyurt
altunyurt

Reputation: 2936

Just an additional info to Sraw's reply:

>>> t = [[]] * 4 
>>> t
[[], [], [], []]
>>> id(t[0]) == id(t[1]) == id(t[2]) == id(t[3])
True
>>> l = [[], []]
>>> id(l[0]) == id(l[1])
False

You get 4 references to same list. That's why adding an element to any of the references show up in the others.

Upvotes: 1

Sraw
Sraw

Reputation: 20224

You cannot use [[]] * 4 to create four lists. In this case, you are just creating one list and four references pointing to it.

So you should use [[] for _ in range(4)].

Upvotes: 6

Related Questions