The filter() built-in function in Python returns an iterator that excludes the elements from the iterable for which the predicate function returns False.
The built-in function filter() returns an instance of class filter, which is an iterator that returns the next item in the iterable(while calling __next()__ on it) for which the predicate function returns True.
If no predicate is passed to the filter() constructor, the __next__() method returns the next element in the iterable that evaluates as True.
Example 1
python
# Example Python program that uses the built-in function
# filter() to exclude a set of elements from an iterable
# for which a specified predicate function returns True.
# A list of colors as RGB tuples
colors = [(255,255,255), # White
(255, 51, 51), # A red variant
(255,128,0), # Orange
(192, 192,192),# A gray variant
(224,224,224), # Another gray variant
(0,0,0)] # Black
# A predicate function returning False for all Gray variants
# and returning True for all other colors
def grayFilter(color):
if color[0] == 255 and color[1] == 255 and color[2] == 255:
return True
elif color[0] == 0 and color[1] == 0 and color[2] == 0:
return True
elif color[0] == color[1] == color[2]:
return False
else:
return True
# Call to built-in function filter to exclude Gray colors
filtered = filter(grayFilter, colors)
print(type(filtered))
# Print the colors after filtering
for color in filtered:
print(color)
# Example Python program that transforms
# a sequence using the built-in function
# filter() and a lambda expression
ASCII_MAX = 127
# Get only ASCII values from the list of
# characters
chars = ["A", "П", "ส", "வ", "ם", "e"]
asciiChars = filter(lambda char:ord(char) <= ASCII_MAX, chars)
for char in asciiChars:
print(char)
Output
Output
A
e
Your privacy choices
We'd like to use Google Analytics cookies to count visits and see which tutorials are useful.
They are only set if you accept. We don't use advertising cookies and we don't sell your data.
You can change your choice any time from “Your privacy choices” at the bottom of every page.
Privacy Policy
Your privacy choices
Your browser sent a Global Privacy Control signal, so analytics is off unless you turn it on here.
Strictly necessary
Remembers this choice in your browser. No cookies, nothing sent to anyone.Always on