Python combine two lists of unequal length in alternating fashion

5.9k views Asked by At

I have a two lists, and I want to combine them in an alternating fashion, until one runs out, and then I want to keep adding elements from the longer list.

Aka.

list1 = [a,b,c]

list2 = [v,w,x,y,z]

result = [a,v,b,w,c,x,y,z]

Similar to this question (Pythonic way to combine two lists in an alternating fashion?), except in these the lists stop combining after the first list has run out :(.

5

There are 5 answers

0
mdurant On BEST ANSWER

Here is the simpler version from the excellent toolz:

>>> interleave([[1,2,3,4,5,6,7,],[0,0,0]])
[1, 0, 2, 0, 3, 0, 4, 5, 6, 7]
2
jonrsharpe On

You might be interested in this itertools recipe:

def roundrobin(*iterables):
    "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
    # Recipe credited to George Sakkis
    pending = len(iterables)
    nexts = cycle(iter(it).next for it in iterables)
    while pending:
        try:
            for next in nexts:
                yield next()
        except StopIteration:
            pending -= 1
            nexts = cycle(islice(nexts, pending))

For example:

>>> from itertools import cycle, islice
>>> list1 = list("abc")
>>> list2 = list("uvwxyz")
>>> list(roundrobin(list1, list2))
['a', 'u', 'b', 'v', 'c', 'w', 'x', 'y', 'z']
2
tcathcart On

My solution:

result = [i for sub in zip(list1, list2) for i in sub]

EDIT: Question specifies the longer list should continue at end of shorter list, which this answer does not do.

0
stephenfin On

You could use plain map and list comprehension:

>>> [x for t in map(None, a, b) for x in t if x]
['a', 'v', 'b', 'w', 'c', 'x', 'y', 'z']
0
Vanjith On

We can use zip_longest with tcathcart answer

import itertools
result = [i for sub in itertools.zip_longest(list1, list2) for i in sub]