LISTS: Extract every other element

Duncan Grisby dgrisby at uk.research.att.com
Fri Dec 17 05:25:31 EST 1999


In article <19991216131341.A153923 at vislab.epa.gov>,
 Randall Hopper  <aa8vb at yahoo.com> wrote:

>I want to take a large list:
>
>  [ 1,2,3,4,5,6,7,... ]
>
>and build a list with every other element:
>
>  [ 1,3,5,7,... ]
>
>Is there a faster way than looping over indices?:

I don't know if it's faster, but how about:

class onoff:
    def __init__(self):
        self.on = 0

    def __call__(self, *args):
        self.on = not self.on
        return self.on

>>> filter (onoff(), [1,2,3,4,5,6,7,8,9])
[1, 3, 5, 7, 9]

It wouldn't be too hard to generalise the onoff class to count in
different patterns.

Cheers,

Duncan.

-- 
 -- Duncan Grisby  \  Research Engineer  --
  -- AT&T Laboratories Cambridge          --
   -- http://www.uk.research.att.com/~dpg1 --



More information about the Python-list mailing list