Feed on
Posts
Comments

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']


Bookmark and Share

if that was helpful ...

check out the other tips and tricks i've compiled on these pages. you might learn something else interesting!

4 Responses to “extract odd or even elements from a python list”

  1. on 02 Nov 2007 at 10:47 am David

    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!)

  2. on 02 Nov 2007 at 11:21 am Lawrence David

    wow, that’s awesome david! thanks for teaching me about list comprehensions … those look very handy!

  3. on 04 Dec 2007 at 5:01 pm Eric Brunson

    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.

  4. on 23 Apr 2011 at 9:23 pm josh

    l[::2] and l[1::2] works too!

Did I get this wrong? Let me know!

Trackback URI | Comments RSS