Skip to content

Instantly share code, notes, and snippets.

@smdabdoub
Created March 21, 2013 14:24
Show Gist options
  • Save smdabdoub/5213405 to your computer and use it in GitHub Desktop.
Save smdabdoub/5213405 to your computer and use it in GitHub Desktop.
Simple python method to create an interleaved list from two or more iterables.
from itertools import chain, izip
ileave = lambda *iters: list(chain(*izip(*iters)))
# full method with doctests
def interleave(*iters):
"""
Given two or more iterables, return a list containing
the elements of the input list interleaved.
>>> x = [1, 2, 3, 4]
>>> y = ('a', 'b', 'c', 'd')
>>> interleave(x, x)
[1, 1, 2, 2, 3, 3, 4, 4]
>>> interleave(x, y, x)
[1, 'a', 1, 2, 'b', 2, 3, 'c', 3, 4, 'd', 4]
On a list of lists:
>>> interleave(*[x, x])
[1, 1, 2, 2, 3, 3, 4, 4]
Note that inputs of different lengths will cause the
result to be truncated at the length of the shortest iterable.
>>> z = [9, 8, 7]
>>> interleave(x, z)
[1, 9, 2, 8, 3, 7]
On single iterable, or nothing:
>>> interleave(x)
[1, 2, 3, 4]
>>> interleave()
[]
"""
return list(chain(*izip(*iters)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment