I am trying to become more familiar with the itertools
module and have found a function called ifilter
.
From what I understand, it filters and iterable based on the given function and returns an iterator over a list containing the elements of the iterable on which the function evaluates to True
.
Question 1: is my understanding thus far correct?
Question 2: aside from the fact that this returns and iterator, how is it different from the built-in filter
function?
Question 3 Which is faster?
From what I can tell, it is not. Am I missing something? (I ran the following test)
>>> itertools.ifilter(lambda x: x%2, range(5)) <itertools.ifilter object at 0x7fb1a101b210> >>> for i in itertools.ifilter(lambda x: x%2, range(5)): print i ... 1 3 >>> filter(lambda x: x%2, range(5)) [1, 3] >>> function = lambda x: x%2 >>> [item for item in range(5) if function(item)] [1,3]
For large lists with one million elements, filtering lists with list comprehension is 40% faster than the built-in filter() method. What is this? The reason is the efficient implementation of the list comprehension statement.
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.
The filter() function is similar to a for-loop in Python but is much fast as a built-in function.
Filter a Python List with filter() The filter(function, iterable) function takes a function as input that takes on argument (a list element) and returns a Boolean value whether this list element should pass the filter. All elements that pass the filter are returned as a new iterable object (a filter object).
Your understanding is corret: the only difference is that ifilter
returns an iterator, while using filter
is like calling:
list(ifilter(...))
You may also be interested in what PEP 289 says about filter and ifilter:
List comprehensions greatly reduced the need for
filter()
andmap()
. Likewise, generator expressions are expected to minimize the need foritertools.ifilter()
anditertools.imap()
. [...]
Also note that ifilter
became filter
in Python-3 (hence removed from itertools).
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