Home > database >  Insert element in list of list from list
Insert element in list of list from list

Time:07-31

Want to insert list elements in list of list such that first element of list should be inserted to first index of first list of list then second element of list of list to first element of 2nd list of list and so on... For eg.

lst_of_lst = [[1,2,3,4][5,6,7,8][9,10,11,12][13,14,15,16]]
list = ['a','b','c','d']

output - lst_of_lst=[['a',1,2,3,4]['b',5,6,7,8]['c',9,10,11,12]['d',13,14,15,16]]

CodePudding user response:

All you need to do is just iterate over your the list you want to insert the items from and just insert the respective item at 0th position.

It can be done as follows:

for i in range(len(list)):
    lst_of_lst[i].insert(0, list[i])

That's it!

Also, you missed , in defining lst_of_lst, it will give you error. And also it is not a good way to name any variable or data structure a name of data type. Like you did for list array. You can change it to _list if you want.

CodePudding user response:

Little trickery for fun/speed:

lst_of_lst = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
list = ['a','b','c','d']

for L, L[:0] in zip(lst_of_lst, zip(list)):
    pass

print(lst_of_lst)

Try it online!

  • Related