I have two lists as follows:
l1 = [1,3,5,7]
and l2 = [2,4,6]
how can I get this output l3 = [1,2,3,4,5,6,7]
,that is, inserting the first entry from l2 as second entry in l1 and so on. Thanks in advance
I have two lists as follows:
l1 = [1,3,5,7]
and l2 = [2,4,6]
how can I get this output l3 = [1,2,3,4,5,6,7]
,that is, inserting the first entry from l2 as second entry in l1 and so on. Thanks in advance
Without assuming the input lists are sorted, or requiring the output be sorted, you can use itertools
for this.
from itertools import zip_longest, chain
l1 = [1,3,5,7]
l2 = [2,4,6]
res = list(filter(None, chain.from_iterable(zip_longest(l1, l2))))
# [1, 2, 3, 4, 5, 6, 7]
Explanation
zip_longest
to iterate lists of unequal length pairwise.chain.from_iterable
to efficiently chain the list of lists.filter(None, ...)
to remove the final None
element.Here is one way that relies on the input lists being sorted in advance in an alternating order like your example, such that you actually want to intercalate them, rather than doing any type of sorted merge.
And that the value None
would never serve as a true value among your lists.
In [12]: from itertools import chain, ifilter, izip_longest
In [13]: list(ifilter(lambda x: x is not None, chain(*izip_longest(l1, l2))))
Out[13]: [1, 2, 3, 4, 5, 6, 7]