Add new item to list in list

I am trying to add a new float element to a list in another list, for example:

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

And I get the following:

 print list [[2.5], [2.5]] 

When I want to receive:

 [[], [2.5]] 

How can i do this?

Thanks in advance.

+6
source share
8 answers

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

+15
source
 list_list = [[] for Null in range(2)] 

do not name it list , which will not allow you to call the built-in list() function.

The reason your problem arises is because Python creates one list , then repeats it twice. So, do you add to it by accessing it either with list_list[0] or with list_list[1] , you do the same so that your changes appear in both indexes.

+5
source

You can make the easiest way ....

 >>> list = [[]]*2 >>> list[1] = [2.5] >>> list [[], [2.5]] 
+3
source
 list = [[]] list.append([2.5]) 

or

 list = [[],[]] list[1].append(2.5) 
+2
source

[] is a list constructor, and in [[]] a list and a sublist are created. *2 duplicates the link to the internal list, but a new list is not created:

 >>> list[0] is list[1] ... True >>> list[0] is [] ... False 

The solution is to have 2 internal lists, list = [[], []]

+2
source

According to @Cat Plus Plus, do not use multiplication. I tried without it. With the same code.

 >> list = [[],[]] >> list[1].append(2.5) >> list >> [[],[2.5]] 
+2
source

you should write something like this:

 >>> l = [[] for _ in xrange(2)] >>> l[1].append(2.5) >>> l [[], [2.5]] 
+1
source

There is another list in the list of the parent list, and when you multiply the list of the outgoing list, all the resulting list items have the same pointer to the internal list. You can create a multidimensional list recursively as follows:

 def MultiDimensionalList(instance, *dimensions):   if len(dimensions) == 1:    return list(     instance() for i in xrange(      dimensions[0]     )    )   else:    return list(     MultiDimensionalList(instance, *dimensions[1:]) for i     in xrange(dimensions[0])    ) print MultiDimensionalList(lambda: None, 1, 1, 0) 

[[]]

0
source

Source: https://habr.com/ru/post/893487/


All Articles