Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading