Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

itertools.ifilter Vs. filter Vs. list comprehensions

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] 
like image 934
inspectorG4dget Avatar asked Jan 24 '12 21:01

inspectorG4dget


People also ask

Which is faster filter or list comprehension?

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.

Is filter a Pythonic?

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.

Is filter fast in Python?

The filter() function is similar to a for-loop in Python but is much fast as a built-in function.

How do you filter a list of objects in Python?

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).


1 Answers

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).

like image 79
Rik Poggi Avatar answered Sep 21 '22 20:09

Rik Poggi