Split a list into half by even and odd indexes?

You can just slice the list: For odd : a[1::2] For even : a[::2]


You can use list slicing. The following snippet will do.

list1 = ['blah', 3, 'haha', 2, 'pointer', 1, 'poop', 'fire']
listOdd = list1[1::2] # Elements from list1 starting from 1 iterating by 2
listEven = list1[::2] # Elements from list1 starting from 0 iterating by 2
print listOdd
print listEven

Output

[3, 2, 1, 'fire']
['blah', 'haha', 'pointer', 'poop']

This should give you what you need - sampling a list at regular intervals from an offset 0 or 1:

>>> a = ['blah', 3,'haha', 2, 'pointer', 1, 'poop', 'fire']
>>> a[0:][::2] # even
['blah', 'haha', 'pointer', 'poop']
>>> a[1:][::2] # odd
[3, 2, 1, 'fire']

Note that in the examples above, the first slice operation (a[1:]) demonstrates the selection of all elements from desired start index, whereas the second slice operation (a[::2]) demonstrates how to select every other item in the list.

A more idiomatic and efficient slice operation combines the two into one, namely a[::2] (0 can be omitted) and a[1::2], which avoids the unnecessary list copy and should be used in production code, as others have pointed out in the comments.

Tags:

Python

List

Split