The built-in function filter() in Python

The filter() built-in function in Python returns an iterator that excludes the elements from the iterable for which the predicate function returns False.

Built-in Functions Updated 21 Jan 2023 1 min read

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

Output

Output
<class 'filter'>

            (255, 255, 255)

            (255, 51, 51)

            (255, 128, 0)

            (0, 0, 0)

Example 2

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