Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 925
Rahul Avatar asked Nov 29 '25 18:11

Rahul


2 Answers

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)]
like image 195
Gerges Avatar answered Dec 01 '25 07:12

Gerges


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)]
like image 23
Rakesh Avatar answered Dec 01 '25 07:12

Rakesh