Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a filter() opposite builtin?

Is there a function in Python that does the opposite of filter? I.e. keeps the items in the iterable that the callback returns False for? Couldn't find anything.

like image 950
Aviv Cohn Avatar asked Nov 29 '15 22:11

Aviv Cohn


People also ask

Is filter a built in function?

Filter() is a built-in function in Python. The filter function can be applied to an iterable such as a list or a dictionary and create a new iterator. This new iterator can filter out certain specific elements based on the condition that you provide very efficiently.

What is filter () function in Python?

The filter() function returns an iterator were the items are filtered through a function to test if the item is accepted or not.

Does filter return a list?

In Python 2, filter() returns an actual list (which is not the efficient way to handle large data), so you don't need to wrap filter() in a list() call.

What is the output of the filter function?

Output: The filtered letters are: e e. Application: It is normally used with Lambda functions to separate list, tuple, or sets. # a list contains both even and odd numbers. seq = [ 0 , 1 , 2 , 3 , 5 , 8 , 13 ]


2 Answers

No, there is no built-in inverse function for filter(), because you could simply invert the test. Just add not:

positive = filter(lambda v: some_test(v), values) negative = filter(lambda v: not some_test(v), values) 

The itertools module does have itertools.ifilterfalse(), which is rather redundant because inverting a boolean test is so simple. The itertools version always operates as a generator.

like image 90
Martijn Pieters Avatar answered Sep 18 '22 09:09

Martijn Pieters


You can do this with itertools.filterfalse or as Martijn suggests, put a not somewhere inside the lambda you use in your filter.

like image 45
El'endia Starman Avatar answered Sep 20 '22 09:09

El'endia Starman