extract odd or even elements from a python list
October 12th, 2007 by Lawrence David
here’s how to extract every other element from a python list using one line of code. to get even elements, use “i%2 == 0″; for odd elements, use “i%2 == 1″.
>>> my_list = ['banana','apple','frog','octopus','pen','spiderman','flower','battery']
>>> map(lambda i: my_list[i],filter(lambda i: i%2 == 0,range(len(my_list))))
['banana', 'frog', 'pen', 'flower']
>>> map(lambda i: my_list[i],filter(lambda i: i%2 == 1,range(len(my_list))))
['apple', 'octopus', 'spiderman', 'battery']
An equivalent (but maybe easier to understand) approach would be to use list comprehensions:
>>> [my_list[i] for i in range(len(my_list)) if i % 2 == 0]
['banana', 'frog', 'pen', 'flower']
>>> [my_list[i] for i in range(len(my_list)) if i % 2 == 1]
['apple', 'octopus', 'spiderman', 'battery']
(Found your site from the \argmax trick btw – thanks!)
wow, that’s awesome david! thanks for teaching me about list comprehensions … those look very handy!
This can be done more simply with subscripting:
>>> x = range(1,10)
>>> print x
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x[::2]
[1, 3, 5, 7, 9]
>>> x[1::2]
[2, 4, 6, 8]
The third arg to the subscript is a step value.
l[::2] and l[1::2] works too!