LISTS: Extract every other element

Charles G Waldman cgw at fnal.gov
Fri Dec 17 12:26:11 EST 1999


Gerrit Holl writes:
 > Randall Hopper 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,... ]
 > 
 > Use the filter() builtin:
 > >>> nums = range(10)
 > >>> print nums
 > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 > >>> def odd(i):
 > ...     return i % 2
 > ...
 > >>> filter(odd, nums)
 > [1, 3, 5, 7, 9]
 > >>> print filter.__doc__
 > filter(function, sequence) -> list
 > 
 > 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.






More information about the Python-list mailing list