15

I'm running into a problem in my program and I'm not sure what I'm doing wrong. To start I created an empty list of lists. For example:

>>> Lists = [[]]*12

which gives:

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

However, when trying to append a value to an individual sublist it adds the value to all of the 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 append to just a single sublist so that the result would look like:

>>> Lists
    [[], [], [1], [], [], [], [], [], [], [], [], []]
user2165857
  • 2,530
  • 7
  • 27
  • 39
  • You may want to look at [this](http://www.laurentluce.com/posts/python-list-implementation/) to understand why it appends to all sublists. If you look at the second figure, you can think of the 12 elements in your list as pointing to the same object `[]`. Now when you append `1` to your `Lists[2]`, it appends to the shared list object. Hence, all elements in `Lists` appear to have the `1` appended. – Nik Jun 21 '13 at 00:22

2 Answers2

25

List objects are mutable, so you're actually making a list with 12 references to one list. Use a list comprehension and make 12 distinct lists:

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

Sorry, I can't find the original duplicate of this exact question

Blender
  • 289,723
  • 53
  • 439
  • 496
2

I ran into this same problem while trying to solve a topological sort problem.

try this:

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