python2
filter(function, iterable)
**Construct a list from those elements of iterable for which function returns true.**
iterable may be either a sequence, a container which supports iteration, or an iterator. If iterable is a string or a tuple, the result also has that type; otherwise it is always a list. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.
Note that filter(function, iterable) is equivalent to [item for item in iterable if function(item)] if function is not None and [item for item in iterable if item] if function is None.
See itertools.ifilter() and itertools.ifilterfalse() for iterator versions of this function, including a variation that filters for elements where the function returns false.
>>> filter(None,range(2,10))
[2, 3, 4, 5, 6, 7, 8, 9]
python3
filter(function, iterable)
**Construct an iterator from those elements of iterable for which function returns true.** iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.
Note that filter(function, iterable) is equivalent to the generator expression (item for item in iterable if function(item)) if function is not None and (item for item in iterable if item) if function is None.
See itertools.filterfalse() for the complementary function that returns elements of iterable for which function returns false.
>>> filter(None,range(2,10))
<filter object at 0x103c87a58>
>>> [x for x in filter(None,range(2,10))]
[2, 3, 4, 5, 6, 7, 8, 9]
>>> list(filter(None,range(2,10)))
[2, 3, 4, 5, 6, 7, 8, 9]