| function | (required ) , Each element is checked through the function |
| iterable | ( required ), iterable object |
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.
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']
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']
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
data = [0, "", None, "Python", [], '0', {}]
filtered_data = filter(None, data)
print(list(filtered_data))
This will output:
['Python', '0']
This demonstrates that filter(None, data) removes elements that are False in a boolean context, such as 0, empty strings, empty lists, and None.
List comprehension can also create a list containing only values that match a condition. See Python list comprehension with conditions.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.