I want to insert an item into a list inside a list. I'm 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:
2. list5 [[(2, 5, 6, 8)], [(1, 2, 3, 4), 2, 5]]
A dictionary unfortunately won't work.
The problem is you are trying to insert as the first element of the list, list5
which is incorrect. You have to access the first element of the list and insert it to that 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]]
The issue here is that insert
creates a new item in the list that it is applied to. So
>>> list5 = [[], [(1,2,3,4), 2, 5]]
creates a list with two elements, the first of which happens to be a list with zero elements:
>>> list5[0]
## []
If you then call list5.insert(0, foo)
, what will happen is that foo
gets pushed into the list at position 0, and everything else gets shoved along (i.e. the elements of the list which had an index of 0 or greater each get their index increased by 1).
What you actually want to do is to insert an element into the empty list at position 0 of list5
. So you need to access that list, and then call a method that adds your element. Either
>>> list5[0].append( (2,5,6,8) )
or
>>> list5[0].insert(0, (2,5,6,8) )
will do the trick.