0

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]
1
  • you need to convert list2 into string format Commented Dec 16, 2022 at 9:01

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.