How to interleave two lists of different length?

This composes a list comprehension using zip_longest from itertools (which is part of the standard library) to interleave items from both lists into a tuple, which by default uses None as the fillvalue.

This also uses chain also from itertools to flatten the list.

Finally it filters the None items from the list:

from itertools import chain, zip_longest
def twolists(l1, l2):
    return [x for x in chain(*zip_longest(l1, l2)) if x is not None]

Or as recommended from @EliKorvigo, use itertools.chain.from_iterable for iterating lazily:

def twolists(l1, l2):
    return [x for x in chain.from_iterable(zip_longest(l1, l2)) if x is not None]

Testing

In [56]: twolists([0, 1], ['w', 'x'])
Out[56]: [0, 'w', 1, 'x']

In [57]: twolists([0, 1], ['w', 'x', 'y', 'z'])
Out[57]: [0, 'w', 1, 'x', 'y', 'z']

In [74]: twolists([0, 1, 2, 3], ['w', 'x'])
Out[74]: [0, 'w', 1, 'x', 2, 3]

Leave a Comment