Skip to content Skip to sidebar Skip to footer

How To Append I'th Element Of A List To First Entry In I'th List In List Of Lists?

That is: each element in a list ends up as the first element in the corresponding list in a list of lists. Like the following: List_of_Lists = [[1,2,3],[2,3,4],[4,4,4]] List1 = [1,

Solution 1:

Another solution:

List_of_Lists = [[1, 2, 3], [2, 3, 4], [4, 4, 4]]
List1 = [1, 2, 3]

out = [[v, *subl] for v, subl inzip(List1, List_of_Lists)]
print(out)

Prints:

[[1, 1, 2, 3], [2, 2, 3, 4], [3, 4, 4, 4]]

Solution 2:

Try this:

for idx, sub_list in enumerate(List_of_Lists):
    sub_list.insert(0, List1[idx])

The above code will modify your List_of_Lists, if you don't want that please create a copy and then loop through the copy.

Solution 3:

Here is a sample code I wrote to insert a value anywhere in sub-lists.

import copy
List_of_Lists = [[1,2,3],[2,3,4],[4,4,4]]
List1 = ['Z','Y','X']

def Insert_List_of_Lists(List_X,index,value):
    temp_list=copy.deepcopy(List_X)
    if index<=len(temp_list):
       for i in range(len(temp_list)):
           temp_list[i].insert(index,value)
    else:
       for i in range(len(temp_list)):
           temp_list[i].insert(len(temp_list),value)
       print("Given index Out of range, value appended")
    return(temp_list)

New_List_of_List = Insert_List_of_Lists(List_of_Lists,3,List1[0])
New_List_of_List

Output:

[[1, 2, 3, 'Z'], [2, 3, 4, 'Z'], [4, 4, 4, 'Z']]

When we try to add a value out of index:

X_list = Insert_List_of_Lists(List_of_Lists,8,'J')
X_list

Output:

Given index Out of range, value appended
[[1, 2, 3, 'J'], [2, 3, 4, 'J'], [4, 4, 4, 'J']]

Post a Comment for "How To Append I'th Element Of A List To First Entry In I'th List In List Of Lists?"