+2 votes
in Programming Languages by (74.2k points)

I am trying to create a list of lists or sets, but when I add/append an element to one of the sublists, the element is added/appened to all other sublits. Here is the example:

>>> t=[[]]*5
>>> t
[[], [], [], [], []]
>>> t[1].append(4)
>>> t
[[4], [4], [4], [4], [4]]

How to solve this error?

1 Answer

+1 vote
by (349k points)
selected by
 
Best answer

Python lists/sets are mutable objects. Each sublist/set in the list has a reference to the same object. That's why when you modify one, the modification is reflected in all. You can solve the issue as follows:

Set

>>> t= [set() for _ in range(3)]

>>> t

[set([]), set([]), set([])]

>>> t[1].add(2)

>>> t

[set([]), set([2]), set([])]

>>> t[2].add(2)

>>> t

[set([]), set([2]), set([2])]

>>> t[2].add(5)

>>> t

[set([]), set([2]), set([2, 5])]

>>> t[2].add(2)

>>> t

[set([]), set([2]), set([2, 5])]

List

>>> t= [[] for _ in range(3)]

>>> t

[[], [], []]

>>> t[1].append(4)

>>> t

[[], [4], []]

by (74.2k points)
It worked like charm.

...