Python itertools ifilter examples

Python itertools.ifilter is efficient way of filtering and looping over a large iterable. Here is the usage for ifilter:

itertools.ifilter(function, iterable)

The function should take one argument and should return boolean value. If true is returned for a value, that value is taken.

Here are some examples.

ifilter on list using function

Given a list of numbers get a new iterable with items less than 100.

import itertools
def is_lt_100(x):
  return x < 100

a = [1,2,3,4,1000]
b = itertools.ifilter(is_lt_100, a)
print b
for i in b:
  print i
<itertools.ifilter object at 0x7fcd030d79d0>
1
2
3
4
Env: Python 2.7.6

ifilter on list using lambda

import itertools
a = [1,2,3,4,1000]
b = itertools.ifilter(lambda x: x < 100, a)
print b
for i in b:
  print i
<itertools.ifilter object at 0x7f7ff889e9d0>
1
2
3
4
Env: Python 2.7.6
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments