views:

536

answers:

3

Can you make it more simple/elegant?

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
+5  A: 
def zigzag(seq):
    return seq[::2], seq[1::2]
cobbal
Only works for lists while the other solution works for any iterable.
Nick Stinemates
true, but title did specify a list
cobbal
+15  A: 

If seq, as you say, is a list, 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
Alex Martelli
SO is making so lazy.
Sridhar Ratnakumar
+6  A: 

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).

Rafał Dowgird