How to insert into a nested list python

I want to insert an item into a list box inside a list box. I am wondering if someone can show me.

list5 = [[], [(1,2,3,4), 2, 5]]
print("1. list5", list5)
list5.insert(0, (2,5,6,8))
print("2. list5", list5)

Output:
1. list5 [[], [(1, 2, 3, 4), 2, 5]]
2. list5 [(2, 5, 6, 8), [], [(1, 2, 3, 4), 2, 5]]

      

I want to:

2. list5 [[(2, 5, 6, 8)], [(1, 2, 3, 4), 2, 5]]

      

The dictionary will unfortunately not work.

+3


source to share


2 answers


The problem is when you are trying to insert as the first element of the list list5

, which is wrong. You have to access the first element of the list and insert it into this list. This can be done using the following code



>>> list5 = [[], [(1,2,3,4), 2, 5]]
>>> print("1. list5", list5)
1. list5 [[], [(1, 2, 3, 4), 2, 5]]
>>> list5[0].insert(0, (2,5,6,8))
>>> print("2. list5", list5)
2. list5 [[(2, 5, 6, 8)], [(1, 2, 3, 4), 2, 5]]

      

+4


source


The problem here is that it insert

creates a new item in the list to which it is applied. So,

>>> list5 = [[], [(1,2,3,4), 2, 5]]

      

creates a list with two elements, the first of which is a list with zero elements:

>>> list5[0]
## []

      

If you then call it list5.insert(0, foo)

, what happens is that it foo

ends up in the list at position 0, and everything else moves forward (i.e., items in the list with index 0 or greater each get their index incremented by 1).



What you really want to do is insert an element into an empty list at position 0 of list5

. Therefore, you need to access this list and then call the method that will add your item. Or

>>> list5[0].append( (2,5,6,8) )

      

or

>>> list5[0].insert(0, (2,5,6,8) )

      

will do the trick.

0


source







All Articles