Home > front end >  how to concatenate two lists in python with numbers and strings?
how to concatenate two lists in python with numbers and strings?

Time:12-17

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]

CodePudding user response:

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.

  • Related