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.
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.
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.
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).
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.
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.
You can do in simplest way....
>>> list = [[]]*2
>>> list[1] = [2.5]
>>> list
[[], [2.5]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With