Search code examples
pythonlistzip

Join 2 elements of a list


If I have 2 lists:

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

How can I get a 3rd list with the output

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

I have tried Zip and Join

but Zip still leaves the items separated and Join removes all the separators entirely

Thanks guys!


Solution

  • To combine two items of two lists as string you need to iterate through both lists at the same time and concatenate the two items as strings.

    list1 = [1, 2, 3, 4]
    list2 = ['a', 'b', 'c', 'd']
    list3 = [str(x) + str(y) for x, y in zip(list1, list2)]
    print(list3)
    

    the output will be:

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