Python adds value to sublist

I have a problem with my program and I'm not sure what I am doing wrong. To start, I created an empty list of lists. For example:

>>> Lists = [[]]*12 

which gives:

 >>> Lists [[], [], [], [], [], [], [], [], [], [], [], []] 

However, when you try to add a value to a separate sublist, it adds the value to all sublists. For example:

 >>> Lists[2].append(1) 

gives:

 >>> Lists [[1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1]] 

Is there a way to add only one sublister so that the result looks like this:

 >>> Lists [[], [], [1], [], [], [], [], [], [], [], [], []] 
+7
source share
2 answers

List objects are mutable, so you make a list with 12 links to one list. Use list comprehension and create 12 separate lists:

 Lists = [[] for i in range(12)] 

Sorry, I can not find the original duplicate of this exact question.

+18
source

I ran into this problem while trying to solve the problem of topological sorting.

try the following:

 Lists[2] = Lists[2]+[1] 
+1
source

All Articles