1

Hello I have a quick question I cant seem to solve.

I have a list:

a = [item1, item2, item3, item4, item5, item6]

And I want to split this list into two seperate ones by everything other item such that:

b = [item1, item3, item5]
c = [item2, item4, item6]
Hunter McMillen
  • 59,865
  • 24
  • 119
  • 170
  • possible duplicate of [Python program to split a list into two lists with alternating elements](http://stackoverflow.com/questions/1442782/python-program-to-split-a-list-into-two-lists-with-alternating-elements) – devnull Mar 04 '14 at 03:19

2 Answers2

6

Use slicing, specifying a step:

b,c = a[::2], a[1::2]
roippi
  • 25,533
  • 4
  • 48
  • 73
0

Using filter is one option:

a = [item1, item2, item3, item4, item5, item6]
b = filter(lambda x: a.index(x) % 2 == 0, a)
c = filter(lambda x: a.index(x) % 2 != 0, a)

EDIT: This would require for the elements to be unique and is inefficient.

shaktimaan
  • 11,962
  • 2
  • 29
  • 33
  • This doesn't work if the list contains equal items, and even when all list elements are unique, it runs in quadratic time instead of linear. – user2357112 Mar 04 '14 at 03:12