Skip to content
Advertisement

Merging two lists in a certain format in Python

I have two lists A and B. I am trying to merge the two lists into one in a specific format as shown in the expected output. I also show the current output.

A=[0, 1]
B=[[1,2],[3,4]]
C=A+B
print(C)

The current output is

[0, 1, [1, 2], [3, 4]]

The expected output is

[[0, 1, 2], [1, 3, 4]]

Advertisement

Answer

lst=[]
for x, y in zip(A, B):
    lst.append([x] + y)
#[[0, 1, 2], [1, 3, 4]]

Or as @Mechanic Pig suggested in comments using list comprehension:

[[a] + b for a, b in zip(A, B)]
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement