Home > Mobile >  How to insert list at specific position into list of lists
How to insert list at specific position into list of lists

Time:02-08

I want to know if it is possible to insert a list of floats into a list of lists at a specific position and how to index it or if I should consider using a different datatype (like an array or dictionary) instead:

As an example:

list_to_insert = [0.7, 0.3, 0.85, -0.1, 0.4]


list_of_lists = [[[], []],
                [[], [], [], [], [], []],
                [[], [], [], [], [], []],
                [[], []]]


=> list_of_lists = [[[], []],
                   [[], [], [], [], [], []],
                   [[], [], [], [], [list_to_insert], []],
                   [[], []]]

CodePudding user response:

You can insert in a list of lists like

list_of_lists[2].insert(4,list_to_insert)

However in the output you gave the element isn't inserted rather replaced. So to get that output

list_of_lists[2][0]=list_to_insert

CodePudding user response:

You can simply specify the index and assign the list at that index. For example, in your example, the following line will get the desired output.

list_of_lists[2][4] = list_to_insert
  •  Tags:  
  • Related