itertools.filterfalse - what is it good for

W

Wolfgang Maier

Dear all,
can anybody point out a situation where you really need itertools.filterfalse() ?
So far, I couldn't think of a case where you couldn't replace it with a
generator expression/if combination.
e.g.,

a=filterfalse(lambda x: x%2, range(1,101))
b=(i for i in range(1,101) if not i % 2)

do not return the same object type, but otherwise are achieving the same thing.
What am I missing here? For sure filterfalse exists for a reason?

Best,
Wolfgang
 
N

Neil Cerutti

Dear all,
can anybody point out a situation where you really need
itertools.filterfalse() ? So far, I couldn't think of a case
where you couldn't replace it with a generator expression/if
combination. e.g.,

a=filterfalse(lambda x: x%2, range(1,101))
b=(i for i in range(1,101) if not i % 2)

do not return the same object type, but otherwise are achieving
the same thing. What am I missing here? For sure filterfalse
exists for a reason?

It must exist for reasons of convenience and efficiency only.

It can trivially be replaced by filter in all cases (at least in
Python 3), but it saves you from a possibly slow extra function
indirection, and also from needing to define one at all.
 
M

Miki Tebeka

can anybody point out a situation where you really need itertools.filterfalse() ?
Sometimes you get the predicate as a parameter to another function. This way if you want to filter out things you can easily do it. Other language (such as Clojure) have a "complement" function that removes the need of filterfalse.

For example (Python 3):
def percent_spam(is_spam, documents):
n_spam = sum(1 for _ in filter(is_spam, documents))
n_ham = sum(1 for _ in filterfalse(is_spam, documents))
return float(n_spam) / (n_ham + n_spam)
 
M

Miki Tebeka

can anybody point out a situation where you really need itertools.filterfalse() ?
Sometimes you get the predicate as a parameter to another function. This way if you want to filter out things you can easily do it. Other language (such as Clojure) have a "complement" function that removes the need of filterfalse.

For example (Python 3):
def percent_spam(is_spam, documents):
n_spam = sum(1 for _ in filter(is_spam, documents))
n_ham = sum(1 for _ in filterfalse(is_spam, documents))
return float(n_spam) / (n_ham + n_spam)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top