user1768884 user1768884 - 11 months ago 54
Python Question

Combining two lists in python3

Suppose I have two lists of any, but equal length, for example:


For these two lists, I would want output to be:

'ar', 'bt', 'cy', 'dh'

Basically, the first element of the first list to the first element of the second list and so on. How would I do that? And note, that the lists can be of any length, not just what the example shows, but the length of the first list is equal to the length of the second list.

agf agf
Answer Source

zip the lists to combine them, then join each pair of strings into a single string:

>>> list1 = ['a','b','c','d']
>>> list2 = ['r','t','y','h']
>>> [''.join(pair) for pair in zip(list1, list2)]
['ar', 'bt', 'cy', 'dh']