'Zipping nested lists

I am trying but am unable to zip the following two lists in a particular way:

list1 = [(1,2,3),(4,5,6),(7,8,9)]
list2 = [10,11,12]
zippedlist = [(1,2,3,10),(4,5,6,11),(7,8,9,12)]

I initially thought unpacking list1 and running zip(*list1,list2) would do the job, but I understand now that will not work.

I suspect this can be done using one or more for-loops with the zip function but I'm not too sure how that'd work. Any advice on how I can proceed?



Solution 1:[1]

Or simply use the + operator in your list comprehension:

list1=[(1,2,3),(4,5,6),(7,8,9)]
list2=[10,11,12]

new_list = [i+(v,) for i,v in zip(list1,list2)]

#[(1, 2, 3, 10), (4, 5, 6, 11), (7, 8, 9, 12)]

Solution 2:[2]

You can also use map:

list(map(lambda x, y: x +(y,), list1, list2))
# [(1, 2, 3, 10), (4, 5, 6, 11), (7, 8, 9, 12)]

Solution 3:[3]

Use zip

Ex:

list1=[(1,2,3),(4,5,6),(7,8,9)]
list2=[10,11,12]

result = [tuple(list(i) + [v]) for i, v in zip(list1, list2)]
print(result)

Output:

[(1, 2, 3, 10), (4, 5, 6, 11), (7, 8, 9, 12)]

Solution 4:[4]

More easy to understand is to spread the tuple and join list 2 then convert it to tuple again.

result = list(map(lambda x, y: (*x, y) , list1, list2))

result = [(1, 2, 3, 10), (4, 5, 6, 11), (7, 8, 9, 12)]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Henry Yik
Solution 2 Gerges
Solution 3 Rakesh
Solution 4 Bob White