Adding items from one list to another list of lists

96 Views Asked by At

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.

4

There are 4 best solutions below

3
Felipe D. On

You can use list comprehension combined with a zip:

desired_output = [[*x, y] for x,y in zip(list_1,list_2)]

print(desired_output)
# [[1, 2, 11], [3, 4, 12], [5, 6, 13], [7, 8, 14]]

Note that *x unpacks the items of list_1, y just takes each individual item from list_2 and [*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.

2
Marat On
zip(*zip(*list_1), list_2)

Explained: there is a canonical way to transpose a list, zip(*lst). All we're doing here is transposing, zipping, and transposing again

2
Alain T. On

You need to add a list and a value for each pairing produced by zip. this requires converting the individual value to a small list (or some other means of creating a merged list):

[s1+[i2] for s1,i2 in zip(list_1,list_2)]
2
computer_goblin On

I might be missing something but can't you just use a .append function?

list_1[0].append(list_2[0])