LISTS: Extract every other element

Neel Krishnaswami neelk at brick.cswv.com
Fri Dec 17 19:28:38 EST 1999


Charles G Waldman <cgw at fnal.gov> wrote:
>Gerrit Holl writes:
>
> > Use the filter() builtin:
> > 
> > Return a list containing those items of sequence for which function(item)
> > is true.  If function is None, return a list of items that are true.
>
>I think that the point was to return a list of the items for which the
>*index* is odd, not the value.

No problem:

  lst = range(10)
  
  class Predicate:
      def __init__(self):
  	  self.x = -1
      def __call__(self, foo):
  	  self.x = self.x + 1
  	  return self.x % 2
  
  print filter(Predicate(), lst)

=> [1, 3, 5, 7, 9]

Of course, this is not very^H^H^H^H at all fast. :)


Neel



More information about the Python-list mailing list