0

I am trying to insert something into a list within a list and I couldn't figure out how to go doing that.

For example, I have a list of lists:

List1 = [[10, 13, 17], [3, 5, 1]]

and I want to insert 5 into sublist with index 0 after element 13 so it would look like this:

List1 = [[10, 13, 5, 17], [3, 5, 1]]
#                 ^ 
Ma0
  • 14,712
  • 2
  • 33
  • 62
Lily Tran
  • 47
  • 2

1 Answers1

2

This will do it. Using .insert() allows you to specify index as well the element and you can do it inplace. No need to assign the output.

List1 = [[10,13,5,17],[3,5,1]]
List1[0].insert(2,5)
print(List1)

Output

[[10, 13, 5, 17], [3, 5, 1]]

Vivek Kalyanarangan
  • 8,499
  • 1
  • 21
  • 39