Merging two lists in a certain format in Python

Question:

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]]
Asked By: AEinstein

||

Answers:

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)]
Answered By: God Is One

You can also use np.insert:

a = np.array([0, 1])
b = np.array([[1, 2], [3, 4]])
np.insert(b, 0, a, axis=1)
Answered By: Hanwei Tang
A=[0, 1]
B=[[1,2],[3,4]]
c=[]
for i in range(len(A)):
    c.append([A[i]])
    for j in range(len(B[i])):
        c[i].append(B[i][j])

print(c)
[[0, 1, 2], [1, 3, 4]]
Answered By: Light
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.