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.
Python filter() Syntax
filter(function, iterable)
As you can see in syntax, filter()
method takes two arguments.
- function (required) – It determines whether or not the items in iterable returns true. If set to None, it removes all false elements and returns true elements only.
- iterable (required) – It can be any iterable (sets, tuples, lists or any).
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
Python filter() Function Example
#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
Python filter() Function Example Without filter() Function
>>> 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.