filter(function, iterable) Construct an iterator using the matching elements from the iterable object
function | (required ) , Each element is checked through the function |
iterable | ( required ), iterable object |
We can pass each element of the iterable object through the function and get only the elements which are matching to condition or returning True.
Example 1
Create one user defined function my_check(). This function receives one element and check if it is divisible by 2 or not. The function will return True if the element is divisible by 2 ( even number ) or it will return False if not divisible by 2.
def my_check(x):
if x%2==0:
return True
else:
return False
my_list=[5,82,40,37] # created a list
my_filter=filter(my_check,my_list)# Used filter
print(list(my_filter)) # display elements
Output
[82, 40]
We used % modulus operator here.
Using string
We know string is also iterable object so we will use one char as input to a function and filter out ( by using if else ) all lower case chars. We will use the string method islower() to check the status of the input char. This method islower() will return True for lower case chars and return False for upper case chars .
def my_check(x):
if x.islower():
return True
else:
return False
my_str='Plus2Net' # input string object
my_filter=filter(my_check,my_str) # used filter
print(list(my_filter)) # output
Output
['l', 'u', 's', 'e', 't']
Using lambda
In above code we have used one user defined function my_check() to check each char of the iterable object. We can also use lambda
in place of my_check() function to get the same functionality.
my_str='Plus2Net'
my_filter=filter(lambda x: x.islower(),my_str)
print(list(my_filter))
Output
['l', 'u', 's', 'e', 't']
Data type of filter() output
By using type() we can findout the data type of the output.
def my_check(x):
if x%2==0:
return True
else:
return False
my_list=[5,82,40,37] # created a list
my_filter=filter(my_check,my_list)# Used filter
print(type(my_filter)) # <class 'filter'>
We can use short code for the function my_check() like this
def my_check(x):
return True if x%2==0 else False
«All Built in Functions in Python slice()
← Subscribe to our YouTube Channel here