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.
Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.