Python’s filter() Function: Iterative Filtering

Learn Python @

Python’s filter() function is a powerful tool for performing iterative data filtering based on a given condition. In this article, we’ll delve into the intricacies of the filter() function, exploring its syntax, usage, and real-world examples.

Understanding the filter() Function:

The filter() function in Python is used to filter elements from an iterable (such as lists, tuples, or sets) based on a specified condition. It takes two arguments: a function that defines the filtering condition and an iterable to be filtered. Let’s dive into some examples:

1. Basic Usage:

# Define a filtering function
def is_even(num):
    return num % 2 == 0

# Filter even numbers from a list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered_numbers = filter(is_even, numbers)

# Convert the filtered result to a list
even_numbers = list(filtered_numbers)



[2, 4, 6, 8, 10]

In this example, the is_even() function defines the filtering condition, and filter() applies this condition to the numbers list, returning only the even numbers.

2. Using Lambda Functions:

Lambda functions provide a concise way to define simple functions inline. They are commonly used with filter() for one-time filtering operations. Let’s see an example:

# Filter positive numbers from a list using a lambda function
numbers = [-3, -2, -1, 0, 1, 2, 3]
positive_numbers = list(filter(lambda x: x > 0, numbers))



[1, 2, 3]

Filtering Names by Length

Let’s use the filter() function to filter names from a list based on their length:

# List of names
names = ["Alice", "Bob", "Ciby", "Deego", "Eve", "Fini"]
# Filter names with length greater than 4
long_names = list(filter(lambda name: len(name) > 4, names))


['<code class="language-python">Ciby', 'Deego', 'Fini'] 
Author: user