Suppose I have the following lists:
list_1 = [[1,2],[3,4],[5,6],[7,8]]
list_2 = [11,12,13,14]
How can I add items from the second list to each of the items from the first one?
Stated clearly, this is the result I'm looking for:
desired_output = [[1, 2, 11], [3, 4, 12], [5, 6, 13], [7, 8, 14]]
What I've tried
I've tried using the zip function, but the results I get are nested:
list(zip(list_1,list_2))
# [((1, 2), 11), ((3, 4), 12), ((5, 6), 13), ((7, 8), 14)]
Notice how it doesn't follow the actual desired output because of the extra degree of nesting.
You can use list comprehension combined with a
zip:Note that
*xunpacks the items oflist_1,yjust takes each individual item fromlist_2and[*x, y]packs them back into one single list. Finally, the list comprehension around all of that takes care of iterating over everything and generating the full list.PS: I'm answering my own question because I was able to figure out the solution on my own while writing the original question. I found hints to the solution in this other thread. But since that other post deals with a slightly different problem, I thought it would be beneficial to write a separate post here dedicated to this specific problem.