4

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.

3 Answers 3

4

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]]
Sign up to request clarification or add additional context in comments.

3 Comments

Glad to be of some help to you, twice :P
Yes, last one was with box = Box().
Nice to see that you remember me :)
1

def add_new_item(l1):

l1[2][2].append(700)
print(l1)

l1 = [10, 20, [300, 400, [5000, 6000], 500], 30, 40]

add_new_item(l1)

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.