list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
output ---
['a', 'b', 'c', 1, 2, 3]
but I want output like this ---
['a',1,'b',2,'c',3]
please help me
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
output ---
['a', 'b', 'c', 1, 2, 3]
but I want output like this ---
['a',1,'b',2,'c',3]
please help me
You can create a for
loop and use zip
and extend
:
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = []
for items in zip(list1, list2):
list3.extend(items)
print(list3)
Alternatively a list comprehension (however it is both slower and less readable, still will keep it here just for information as to how to handle cases where an iterable has to be extended in a comprehension)
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = [c for items in zip(list1, list2) for c in items]
print(list3)
from itertools import chain
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
result = list(chain(*zip(list1, list2)))
print(result)
As a [better] alternative (because argument you pass to .from_iterable()
will be evaluated lazily), as mentioned by @juanpa.arrivillaga:
result = list(chain.from_iterable(zip(list1, list2)))
A brute-force merge will go something like this:
list1 = ['a', 'b', 'c']
list2 = [1, 2, 3]
list3 = []
## merge two list with output like ['a',1,'b',2,'c',3]
for i in range(len(list1)):
list3.append(list1[i])
list3.append(list2[i])
print(list3)
A better way is to use itertool or chain as above!