I am trying to become more familiar with the itertools module and have found a function called ifilter.
From what I understand, it filters
The example below includes a number generator that prints a message immediately before yielding the number, shows up how filter() first builds the list, then runs through that and filters it. Whereas itertools.ifilter filters as it goes, never building a list. If you're filtering 500,000 significant things, you want ifilter, so you're not building a list.
import itertools
def number_generator():
for i in range(0, 3):
print "yield", i
yield i
print "stopping"
function = lambda x: x > 0
numbers = number_generator()
print "itertools.ifilter:"
for n in itertools.ifilter(function, numbers):
print n
print "\nfilter:"
numbers = number_generator()
for n in filter(function, numbers):
print n
Output:
itertools.ifilter: yield 0 yield 1 1 yield 2 2 stopping filter: yield 0 yield 1 yield 2 stopping 1 2