The Python filter()
function constructs an iterator from those elements of iterable for which function returns true. In simple words, filter()
returns a sequence from those elements of iterable for which the function returns true.
filter(function, iterable)
As you can see in syntax, filter()
method takes two arguments.
If the function is defined, then filter(function, iterable)
is equivalent to:
item for item in iterable if function(item)
And when the function is not defined (i.e is None), filter(function, iterable)
is equivalent to:
item for item in iterable if item
#defining a filter function
def func(x):
if(x>0):
return True
else:
return False
#Using the function to filter the list
a = filter(func, [-2, -1, 0, 1, 2])
for i in a:
print(i)
This above script will generate following output.
1 2
>>> f = filter((0, 1, True, False, None))
>>> for i in f:
print(i)
1
True
Here in above example as you can see, when filter function is not defined, filter()
method returns only True values.