12

I know there are many chunky ways to do this, but I am looking for a slick pythonic way to accomplish the following. Given a list of numbers:

a = [0,1,2,3,4,5,6,7,8,9]

split this list into 2 lists corresponding to every other element:

b = [0,2,4,6,8]
c = [1,3,5,7,9]
user1452494
  • 1,145
  • 5
  • 18
  • 40

3 Answers3

24

You want:

b = a[::2]  # Start at first element, then every other.

and:

c = a[1::2]  # Start at second element, then every other.

So now we have what we want:

>>> print(b)
[0, 2, 4, 6, 8]
>>> print(c)
[1, 3, 5, 7, 9]
anon582847382
  • 19,907
  • 5
  • 54
  • 57
5

You can do that using list slicing:

b = a[::2]
c = a[1::2]

Example

>>> a = [0,1,2,3,4,5,6,7,8,9]

>>> b = a[::2]
>>> c = a[1::2]

>>> print b
[0,2,4,6,8]

>>> print c
[1,3,5,7,9]

The [::] syntax is as follows: [start:end:step]. If you don't specify any parameters for start and end, it will work with the whole list. Therefore, what the code above is doing is:

For b: start at index 0, take every other element from a
For c: start at index 1, take every other element from a

sshashank124
  • 31,495
  • 9
  • 67
  • 76
1

Try This :

a = [0,1,2,3,4,5,6,7,8,9]
>>> b=[i for x,i in enumerate(a) if x%2==1]
>>> c=[i for x,i in enumerate(a) if x%2==0]
>>> b
  [1, 3, 5, 7, 9]
>>> c
  [0, 2, 4, 6, 8]
sshashank124
  • 31,495
  • 9
  • 67
  • 76
Sakam24
  • 121
  • 5
  • You are not splitting according to indices, but according to list elements. Just try to split [1,13,75,23,11,17]... –  Apr 17 '14 at 10:31
  • Okay now. However I would have swapped x and i, it would be more intuitive! –  Apr 17 '14 at 10:46