Search code examples
pythonlistpython-2.7alternation

Python combine two lists of unequal length in alternating fashion


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


Solution

  • 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]