Merge List in Python next to the same index

Question:

I have two list, i wanted to merge both the list in next to the same index with the delimiter.

list1 = ['1', '2', '3', '4']
list2 = ['A', 'B', 'C', 'D']

Expected result,

['1 - A', '2 - B', '3 - C', '4 - D']

I can merge both the lists using Concatenate, append or extend methods. But not sure to concatenate with the delimiter of every equivalent record.

Asked By: Jim Macaulay

||

Answers:

Try this using zip() and list comprehension:

list1 = ['1', '2', '3', '4']
list2 = ['A', 'B', 'C', 'D']


result = [f'{i} - {j}' for i,j in zip(list1, list2)]

the result will be:

Out[2]: ['1 - A', '2 - B', '3 - C', '4 - D']
Answered By: Mehrdad Pedramfar

Without using zip():

[n+' - '+list2[i] for i, n in enumerate(list1)]

or

[list1[i]+' - '+list2[i] for i in range(len(list1))]
Answered By: Arifa Chan
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.