TimLayne
TimLayne

Reputation: 124

Regarding the use of filter()

Ive been studying the built-in-functions for python for a while now, im trying to have a firm grasp of ideal situations to apply them for later. Ive understood all of them except filter(), the arguments being filter(function, iterable). In docs.python.org it states:

If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

I decided to work off of that since I didn't grasp what function was asking(obviously, it needs a function;however, what kind?)This is what tried:

a=filter(None,[1,0,1,0,1,0])
<filter object at 0x02898690>
callable(a)
False

My Question: If the filter object isn't callable, then where is it applicable?

Upvotes: 0

Views: 102

Answers (3)

rlms
rlms

Reputation: 11060

Example usage:

>>> list(filter(None, [0, 1, 2, 0, 3, 4, 5, "", 6, [], 7, 8]))
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> def is_multiple_of_two_or_three(x):
        return x % 2 == 0 or x % 3 == 0
>>> list(filter(is_multiple_of_two_or_three, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
[0, 2, 3, 4, 6, 8, 9]

With the lambda keyword, we could write that as list(filter(lambda x: x%3 == 0 or x%2 == 0, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])).

In Python 2.x we would get the same results if we removed the call to list. In Python 3.x, we could iterate through a filter object without it with for i in filter(None, something), but I put in a call to list to show the results (the string representation of an iterable isn't usually that helpful).

The function filter is one of the parts of Python (along with map, reduce and the functools and itertools modules) that are part of the programming paradigm of functional programming.

Upvotes: 1

jonrsharpe
jonrsharpe

Reputation: 121986

Note that:

"none" != None

What the documentation is saying is that if the function is None:

filter(None, iterable)

It assumes that you only want the items in iterable for which bool(item) == True.

To actually provide a function to filter, it is common to use lambda:

filter(lambda x: x > 5, iterable)

or define a function:

def some_func(x):
    return x > 5

filter(some_func, iterable)

The filter object isn't callable, but it is iterable:

a = filter(None, iterable)
for item in a:
    print item

Upvotes: 2

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250911

Function can be any python function:

def based function:

def func(x):
    return x != 0

>>> list(filter(func, [1,0,1,0,1,0]))
[1, 1, 1]

lambda:

>>> list(filter(lambda x: x!=0, [1,0,1,0,1,0]))
[1, 1, 1]

And in Python3 filter returns an iterator. It never returns a callable.

Upvotes: 0

Related Questions