Exploring the filter Function

Lesson Introduction

The filter function helps create filtered views of data. By the end of this lesson, you'll know how to use the filter function effectively, both with lambda functions and predefined functions.

Introducing the filter Function

The filter function is built into Python to create an iterator from elements of an iterable that satisfy a function. It’s useful for extracting specific elements from a list, tuple, or any iterable based on a condition.

Here’s the basic syntax:

filter(function, iterable)
  • function: A function that tests elements in the iterable.
  • iterable: Any iterable (e.g., list, tuple).

Example: Filtering Even Numbers

Let's see a basic example. Suppose you have a list of numbers and want to keep only the even numbers:

def is_even(x):
    return x % 2 == 0

if __name__ == "__main__":
    # List of numbers
    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

    # Filter even numbers
    evens = list(filter(is_even, numbers))
    print("Even numbers:", evens)  # Even numbers: [2, 4, 6, 8, 10]

The is_even function checks if a number is even. The filter function keeps only elements for which is_even returns True.

Using filter with Lambda Functions

As before, we can utilize lambdas to make the code more clean. Here’s how to use a lambda function to filter even numbers:

if __name__ == "__main__":
    # List of numbers
    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

    # Filter even numbers using lambda
    evens = list(filter(lambda x: x % 2 == 0, numbers))
    print("Even numbers:", evens)  # Even numbers: [2, 4, 6, 8, 10]

The lambda function lambda x: x % 2 == 0 does the same job as is_even, but more concisely.

Using filter with Predefined Functions: Part 1

Predefined functions are helpful when you have a complex condition. Let’s filter out prime numbers from a list. First, define a function to check if a number is prime:

def is_prime(x):
    if x < 2:
        return False
    for i in range(2, int(x ** 0.5) + 1):
        if x % i == 0:
            return False
    return True
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal