[Tutor] Filter

dman dsh8290@rit.edu
Sat, 27 Oct 2001 22:44:07 -0400


On Sat, Oct 27, 2001 at 07:49:24PM -0600, Mike Yuen wrote:
| I'm having some trouble understanding how to use the filter function.  My
| understanding is that say I have a series of numbers like:
| 
| 4732789123895231

What do you mean by a "series"?  Is it a list, tuple, string,
something else?

| And I want to remove all occurences of 1,2,3.
| 
| How do I do this?


>>> def should_keep( num ) :
...    return num not in ( 1 , 2 , 3 )
...
>>> my_series = [ 4,7,3,2,7,8,9,1,2,3,8,9,5,2,3,1 ]
>>> print filter( should_remove , my_series )
[4, 7, 7, 8, 9, 8, 9, 5]
>>>


You define a function that returns a boolean indicating whether or not
you want to keep the specified element.  The filter function runs
through the sequence ("my_series") and calls the function
("should_remove") passing each element in turn as the argument.  For
those elements for which the function returns true, it puts it into a
new list.  The others are ignored.  filter then returns that new list
it built.


Another technique is to use list comprehensions.  This requires python
2.0 or newer.

>>> my_series = [ 4,7,3,2,7,8,9,1,2,3,8,9,5,2,3,1 ]
>>> print [x for x in my_series if x not in (1,2,3) ]
[4, 7, 7, 8, 9, 8, 9, 5]
>>>


It is more compact, though it is a little harder to become familiar
with, I think.

HTH,
-D