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

how to concatenate two lists in python with numbers and strings?

i want to merge two lists together, but not one after the other

list1=[1,2,3,4]
list2=[a,b,c,d,e,f]

and the output should be

list3=[1a,2b,3c,4d,e,f]

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

>Solution :

Use itertools.zip_longest to iterate over lists of uneven length, and provide a default value (fillvalue) for the missing elements.

from itertools import zip_longest

list1 = [1, 2, 3, 4]
list2 = ["a", "b", "c", "d", "e", "f"]

res = [f"{a}{b}" for a, b in zip_longest(list1, list2, fillvalue="")]
print(res)

Output

['1a', '2b', '3c', '4d', 'e', 'f']

The expression f"{a}{b}" is known as an f-string and is used to format strings.

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