To filter
discards elements of a sequence based on some criteria:
names = ['Fred', 'Wilma', 'Barney']
def long_name(name):
return len(name) > 5
filter(long_name, names)
# Out: ['Barney']
[name for name in names if len(name) > 5] # equivalent list comprehension
# Out: ['Barney']
from itertools import ifilter
ifilter(long_name, names) # as generator (similar to python 3.x filter builtin)
# Out: <itertools.ifilter at 0x4197e10>
list(ifilter(long_name, names)) # equivalent to filter with lists
# Out: ['Barney']
(name for name in names if len(name) > 5) # equivalent generator expression
# Out: <generator object <genexpr> at 0x0000000003FD5D38>
# Besides the options for older python 2.x versions there is a future_builtin function:
from future_builtins import filter
filter(long_name, names) # identical to itertools.ifilter
# Out: <itertools.ifilter at 0x3eb0ba8>
filter(long_name, names) # returns a generator
# Out: <filter at 0x1fc6e443470>
list(filter(long_name, names)) # cast to list
# Out: ['Barney']
(name for name in names if len(name) > 5) # equivalent generator expression
# Out: <generator object <genexpr> at 0x000001C6F49BF4C0>