How to split an iterable into two lists with alternating elements

If seq is a sequence, then:

def zigzag(seq):
  return seq[::2], seq[1::2]

If seq is a totally generic iterable, such as possibly a generator:

def zigzag(seq):
  results = [], []
  for i, e in enumerate(seq):
    results[i%2].append(e)
  return results

This takes an iterator and returns two iterators:

import itertools
def zigzag(seq):
    t1,t2 = itertools.tee(seq)
    even = itertools.islice(t1,0,None,2)
    odd = itertools.islice(t2,1,None,2)
    return even,odd

If you prefer lists then you can return list(even),list(odd).


def zigzag(seq):
    return seq[::2], seq[1::2]