Next / Previous / Contents / TCC Help System / NM Tech homepage

20.14. filter(): Extract qualifying elements from an iterable

This function is useful for removing some of the elements of an iterable. You must provide a filtering function that takes one argument and returns a bool value. Here is the calling sequence:

filter(f, S)

The filtering function f is the first argument. It is applied to every element of some iterable S. The result is a new sequence containing only those elements x of S for which f(x) returned True.

>>> def isOdd(x):
...     if (x%2) == 1: return True
...     else: return False
... 
>>> filter(isOdd, [88, 43, 65, -11, 202])
[43, 65, -11]
>>> filter(isOdd, (1, 2, 4, 6, 9, 3, 3))
(1, 9, 3, 3)
>>> def isLetter(c):
...     return c.isalpha()
... 
>>> filter(isLetter, "01234abcdeFGHIJ*(&!^")
'abcdeFGHIJ'
>>> maybes = [0, 1, (), (2,), 0.0, 0.25]
>>> filter(None, maybes)
[1, (2,), 0.25]
>>> filter(bool, maybes)
[1, (2,), 0.25]