Introduction
The filter() method in python filters the given collection or sequence with the help of a function which tests each element in the sequence holds true or not.
Syntax
Below is the syntax used for defining the filter function:
filter(function, sequence)
Parameters
Parameters used by Python filter() function is enlisted below:
- function: it is the function that tests if each element of a sequence true or not.
- sequence: it is the sequence which needs to be filtered, it can be sets, lists, tuples, or containers of any iterators.
Return Value
This function returns an filtered iterator that can be iterated upon.
Examples
Example 1: Using filter() function with a normal function
Here, we are using filter() function by passing a normal function to filter values from the list.
Output:
Example 2: Using filter() function with a lambda function
Here, we are using filter() function by passing a lambda function to filter values from the list.
Output:
Example 3: Using filter() function for filtering vowels and consonants
Here, we are using filter() function for filtering vowels and consonants
Output: