Joining two lists to create a new list

Viewed 84

I have two lists and a constant number

x =[47, 78, 35, 70, 28, 41]
y = [45, 79, 30, 83, 71, 46]
z=10

I want to create a new list which looks like

a=[[47,45,10],
   [78,79,10],
   [35,30,10],
   [70,83,10],
   [28,71,10],
   [41,46,10]]
2 Answers

Try this

res = [[a, b, z] for a, b in zip(x, y)]
print(res)

Output:

[[47, 45, 10],
 [78, 79, 10],
 [35, 30, 10],
 [70, 83, 10],
 [28, 71, 10],
 [41, 46, 10]]

Itertools has similar functionality with zip_longest and it's a quicker than zip

from itertools import zip_longest

[[a, b, z] for a,b in zip_longest(x,y)]

>>> 
[[47, 45, 10],
 [78, 79, 10],
 [35, 30, 10],
 [70, 83, 10],
 [28, 71, 10],
 [41, 46, 10]]
Related