Home > Software engineering >  How to add an element into list inside another list?
How to add an element into list inside another list?

Time:01-13

I need to add an element into a list which is inside another one In my case i wanted to add 800 after 700

strange_list = [1, 2, [30, 40, [500, 600, 700], 80], 8]
strange_list.insert(2[2[2]], 800)

I tried something like this, but i'm getting an error

CodePudding user response:

The line strange_list.insert(2[2[2]], 800) is incorrect, because you cannot use this to specify where to insert the 800. Try this:

strange_list = [1, 2, [30, 40, [500, 600, 700], 80], 8]
strange_list[2][2].insert(3, 800)

First, strange_list[2][2] access the list [500, 600, 700]. Next, .insert(3, 800) adds the number 800 as the 4th element of the list [500, 600, 700], turning it into [500, 600, 700, 800].

CodePudding user response:

Your access by index seems faulty. Try the following:

strange_list[2][2].insert(3, 800)

I.e. access 3rd element of original list, then 3rd element of [30, 40, [500, 600, 700], 80] which is [500, 600, 700] and insert at the 4th position.

CodePudding user response:

You can use insert: list.insert(pos, val)

Check this solution out:

strange_list[2][2].insert(3, 800)

Hope this helps!

  • Related