itertools.ifilter Vs. filter Vs. list comprehensions

inspectorG4dget picture inspectorG4dget · Jan 24, 2012 · Viewed 19.8k times · Source

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]

Answer

Rik Poggi picture Rik Poggi · Jan 25, 2012

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() and map(). Likewise, generator expressions are expected to minimize the need for itertools.ifilter() and itertools.imap(). [...]

Also note that ifilter became filter in Python-3 (hence removed from itertools).