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 is the first argument. It is applied to every
element of some iterable f. The result is a new sequence containing only
those elements S
of x for which
S returned f(x)True.
If is a
string or tuple, the result has the same type, otherwise
the result is a flist.
If is fNone, you get a sequence of the true elements of
. In this
case, the filtering function is effectively the Sbool()
function.
>>> 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]