0

I want to split a list into 2 lists where the elements from the original list are put alternating into the new lists. Here's a simple example with the expected output.

l = ['a', 'b', 'c', 'd', 'e', 'f']

=> 
['a', 'c', 'e']
['b', 'd', 'f']

I expected an existing solution for this in itertools, but couldn't find anything that fit. I also couldn't find any solution here. Eventually I went with the following solution. It works good enough, is short/readable, but is not efficient (iterating the original list twice, and using indices instead of iterators).

l1 = [l[i] for i in range(0, len(l), 2)]
l2 = [l[i] for i in range(1, len(l), 2)]

Now I'm curious. Is there an existing, generic solution that is both short AND efficient?

Florian Braun
  • 321
  • 1
  • 5

1 Answers1

1

You can slice lists with the syntax l[start:stop:increment]. So in your case it would be l[::2] and l[1::2]. If you leave the argument blank, the default values are 0, len(l), and 1 respectively.

alexpiers
  • 696
  • 5
  • 12