thecarny
thecarny

Reputation: 11

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,2,3]

Resulting:

New_List_of_List = [[1,1,2,3][2,2,3,4],[3,4,4,4]]

I have tried various append and insert methods, but the main problem is that I'm not sure how to mash up individual lists in List_of_Lists and elements in List.

Upvotes: 0

Views: 1871

Answers (4)

Mohamed Suhaib
Mohamed Suhaib

Reputation: 13

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']]

Upvotes: 0

Shivam Roy
Shivam Roy

Reputation: 2061

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.

Upvotes: 0

Andrej Kesely
Andrej Kesely

Reputation: 195478

Another solution:

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

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

Prints:

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

Upvotes: 1

user15801675
user15801675

Reputation:

You can insert the elements at the 0 position

lists = [[1,2,3],[2,3,4],[4,4,4]]
List1 = [1,2,3]
for i in range(len(lists)):
    
     lists[i].insert(0,List1[i])
print(lists)

Output:

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

Upvotes: 1

Related Questions