1

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 :(.

Community
  • 1
  • 1
Beth
  • 51
  • 1
  • 6

5 Answers5

5

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']
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
5

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]
mdurant
  • 27,272
  • 5
  • 45
  • 74
1

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']
stephenfin
  • 1,447
  • 3
  • 20
  • 41
0

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.

tcathcart
  • 54
  • 1
0

We can use zip_longest with tcathcart answer

import itertools
result = [i for sub in itertools.zip_longest(list1, list2) for i in sub]
Vanjith
  • 520
  • 4
  • 23