Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append a new item to a list within a list

I'm trying to append a new float element to a list within another list, for example:

list = [[]]*2
list[1].append(2.5)

And I get the following:

print list
[[2.5], [2.5]]

When I'd like to get:

[[], [2.5]]

How can I do this?

Thanks in advance.

like image 372
Varsovilla Avatar asked Jul 25 '11 10:07

Varsovilla


People also ask

How do you add an item to a list inside a list?

There are four methods to add elements to a List in Python. append(): append the object to the end of the list. insert(): inserts the object before the given index. extend(): extends the list by appending elements from the iterable.

Can you append two things at once to a list in Python?

You can use the sequence method list. extend to extend the list by multiple values from any kind of iterable, being it another list or any other thing that provides a sequence of values. So you can use list. append() to append a single value, and list.

Can we append a list to a list?

append() adds a list inside of a list. Lists are objects, and when you use . append() to add another list into a list, the new items will be added as a single object (item).


3 Answers

lst = [[] for _ in xrange(2)] (or just [[], []]). Don't use multiplication with mutable objects — you get the same one X times, not X different ones.

like image 61
Cat Plus Plus Avatar answered Sep 29 '22 19:09

Cat Plus Plus


list_list = [[] for Null in range(2)]

dont call it list, that will prevent you from calling the built-in function list().

The reason that your problem happens is that Python creates one list then repeats it twice. So, whether you append to it by accessing it either with list_list[0] or with list_list[1], you're doing the same thing so your changes will appear at both indexes.

like image 35
agf Avatar answered Sep 29 '22 19:09

agf


You can do in simplest way....

>>> list = [[]]*2
>>> list[1] = [2.5]
>>> list
[[], [2.5]]
like image 21
Manoj Suryawanshi Avatar answered Sep 29 '22 20:09

Manoj Suryawanshi