How to split an iterable into two lists with alternating elements

Viewed 11222

I want to split an iterable into two lists with alternating elements. Here is a working solution. But is there a simpler way to achieve the same?

def zigzag(seq):
    """Return two sequences with alternating elements from `seq`"""
    x, y = [], []
    p, q = x, y
    for e in seq:
        p.append(e)
        p, q = q, p
    return x, y

Sample output:

>>> zigzag('123456')
(['1', '3', '5'], ['2', '4', '6'])
4 Answers

I just wanted to clear something. Say you have a list

list1 = list(range(200))

you can do either :

## OPTION A ##
a = list1[1::2]
b = list1[0::2]

or

## OPTION B ##
a = list1[0:][::2] # even
b = list1[1:][::2] # odd

And get have alternative elements in variable a and b.

But OPTION A is twice as fast

Related