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.
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.
The filter() function returns an iterator were the items are filtered through a function to test if the item is accepted or not.
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.
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 ]
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.
You can do this with itertools.filterfalse
or as Martijn suggests, put a not
somewhere inside the lambda you use in your filter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With