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.
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.You can do in simplest way....
you should write something like this:
dont call it
list
, that will prevent you from calling the built-in functionlist()
.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 withlist_list[1]
, you're doing the same thing so your changes will appear at both indexes.or
As per @Cat Plus Plus dont use multiplication.I tried without it.with same your code.