Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python appending a value to a sublist [duplicate]

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], [], [], [], [], [], [], [], [], []]
like image 676
user2165857 Avatar asked Jun 20 '13 23:06

user2165857


People also ask

How do you append to a sublist in Python?

Using + Operator The + operator when used with a list simply adds new elements to each of the list items. In the below example we find that even a list itself can be used as a new element to be added to the existing lift. Also the existing elements in the list can be of varying length.

How do you add the same value to a list multiple times in python?

Use the multiplication operator to create a list with the same value repeated N times in Python, e.g. my_list = ['abc'] * 3 . The result of the expression will be a new list that contains the specified value N times.

How do you repeat a list of elements in Python?

The * operator can also be used to repeat elements of a list. When we multiply a list with any number using the * operator, it repeats the elements of the given list. Here, we just have to keep in mind that to repeat the elements n times, we will have to multiply the list by (n+1).


1 Answers

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

like image 190
Blender Avatar answered Sep 22 '22 19:09

Blender