Python Filter Function 

In this tutorial, you will learn about Filter Function In Python

Introduction


The filter() function in Python is a built-in function that offers a convenient way to filter elements from an iterable based on a specified condition.

It takes a function and an iterable as input and returns a new iterable containing only the elements for which the function returns True.

This chapter provides a comprehensive tutorial on how to use the filter() function effectively in Python.


Syntax of filter() Function


The basic syntax for the filter() function is as follows:

filter(function, iterable)

function: A function that tests whether each element of an iterable returns True or False.

iterable: The iterable to be filtered.


Using filter() with Simple Functions


# Define a function to filter even numbers
def is_even(num):
    return num % 2 == 0

# Create a list of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Use filter() to get only even numbers
even_numbers = filter(is_even, numbers)

# Convert the filter object to a list
result = list(even_numbers)

print(result)

 

Lambda Functions with filter()


Using lambda functions with filter() is a common practice for short and simple filtering conditions.

# Create a list of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Use filter() with a lambda function to get only even numbers
even_numbers = filter(lambda x: x % 2 == 0, numbers)

# Convert the filter object to a list
result = list(even_numbers)

print(result)

 

Filtering Sequences


a. Lists

# Create a list of words
words = ["apple", "banana", "cherry", "date"]

# Use filter() to get words starting with 'b'
filtered_words = filter(lambda x: x.startswith('b'), words)

# Convert the filter object to a list
result = list(filtered_words)

print(result)

b. Tuples

# Create a tuple of temperatures
temperatures = (25, 30, 18, 22, 28, 15)

# Use filter() to get temperatures above 20 degrees
filtered_temps = filter(lambda x: x > 20, temperatures)

# Convert the filter object to a tuple
result = tuple(filtered_temps)

print(result)

c. Strings

# Create a string of characters
characters = "abracadabra"

# Use filter() to get only vowels
filtered_vowels = filter(lambda x: x in 'aeiou', characters)

# Convert the filter object to a string
result = ''.join(filtered_vowels)

print(result)

 

Filtering with None as the Function


Using None as the function in filter() keeps only the elements that are true in a boolean context.

# Create a list with a mix of values
mixed_values = [0, 1, "", "hello", None, True, False]

# Use filter() with None to get only truthy values
filtered_values = filter(None, mixed_values)

# Convert the filter object to a list
result = list(filtered_values)

print(result)

 

Practical Examples


a. Filtering Even Numbers

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))

print(even_numbers)

b. Filtering Prime Numbers

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

numbers = range(20)
prime_numbers = list(filter(is_prime, numbers))

print(prime_numbers)

c. Removing Empty Strings from a List

words = ["apple", "", "banana", "cherry", "", "date"]
non_empty_words = list(filter(lambda x: x != "", words))

print(non_empty_words)

 

Summary


The filter() function is a powerful tool for selectively extracting elements from iterables based on user-defined conditions. Whether you use simple functions, lambda functions, or the None trick, filter() provides a flexible and concise way to work with data. Understanding how to leverage this function enhances your ability to write clean and efficient Python code.
 

© 2022-2023 All rights reserved.