Home > Software design >  Merge List in Python next to the same index
Merge List in Python next to the same index

Time:11-16

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.

CodePudding user response:

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']

CodePudding user response:

Without using zip():

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

or

[list1[i] ' - ' list2[i] for i in range(len(list1))]
  • Related