Python filter()
Python filter() builtin function is used to filter elements of an iterable based on a function. Elements of the iterable for which the return value of function is True, make it to the result.
In this tutorial, we will learn about the syntax of Python filter() function, and learn how to use this function with the help of examples.
Syntax
The syntax of filter() function is
filter(function, iterable)
where
Parameter | Required/ Optional | Description |
---|---|---|
function | Required | Python function that filters the given iterable. |
iterable | Required | Iterable to be filtered. |
Returns
The function returns a filter object. We can typecast it to required collection type.
Examples
1. Filter Even Numbers from List
In this example, we take a list of integers and filter only even values in it.
Python Program
def even(x):
return x % 2 == 0
a = [2, 5, 7, 8, 10, 13, 16]
result = filter(even, a)
print('Original List :', a)
print('Filtered List :', list(result))
Output
Original List : [2, 5, 7, 8, 10, 13, 16]
Filtered List : [2, 8, 10, 16]
2. Filter with Lambda Function
We can also provide a lambda function for function parameter of filter().
Python Program
a = [2, 5, 7, 8, 10, 13, 16]
result = filter(lambda x: x % 2 == 0, a)
print('Original List :', a)
print('Filtered List :', list(result))
Output
Original List : [2, 5, 7, 8, 10, 13, 16]
Filtered List : [2, 8, 10, 16]
3. Remove Vowels from String
In this example, we take a string and remove vowels from string by filtering only those characters that are not vowels.
Python Program
a = 'Hello World'
result = filter(lambda x: x.lower() not in ['a', 'e', 'i', 'o', 'u'], a)
result = ''.join(list(result))
print('Original List :', a)
print('Filtered List :', result)
Output
Original List : Hello World
Filtered List : Hll Wrld
Conclusion
In this Python Tutorial, we have learnt the syntax of Python filter() builtin function, and also learned how to use this function, with the help of Python example programs.