The Built-in Function Filter() In Python

Overview:

  • 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:

# 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)

Output:

<class 'filter'>
(255, 255, 255)
(255, 51, 51)
(255, 128, 0)
(0, 0, 0)

 


Copyright 2023 © pythontic.com