Skip to content Skip to sidebar Skip to footer

Merge Lists In Python

I have 2 lists: (list1, list2) and I need to merge these lists to another list which contains list1 and list2 in this order: listNew = [list1(i), list2(i), list1(i+1), list2(i+1),

Solution 1:

I want to point out the very convenient itertools.chain():

from itertools import chain

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

listNew = list(chain.from_iterable(zip(list1, list2)))
# listNew = ['1', 'a', '2', 'b', '3', 'c']

You could also use a list comprehension with a double-loop:

listNew = [y forxinzip(list1, list2) foryin x]
# listNew = ['1', 'a', '2', 'b', '3', 'c']

If you want to concatenate pairs of elements in your listNew, that is simply:

listNew_ = [x + y for x, y inzip(list1, list2)]
# listNew_ = ['1a', '2b', '3c']

Solution 2:

merged_list = []
length = min([len(list1), len(list2)])
for l in range(0,length):
   merged_list.append(list1[l])
   merged_list.append(list2[l])

print merged_list

Post a Comment for "Merge Lists In Python"