How to Filter a List in Python

Avatar

By squashlabs, Last Updated: Sept. 17, 2024

How to Filter a List in Python

Overview of List Comprehension

List comprehension allows you to create new lists by iterating over existing ones and applying certain conditions. It provides a way to filter elements from a list based on specific criteria. With list comprehension, you can perform filtering, transformation, and combination of elements in a single line of code, making your code more readable and expressive.

Related Article: Python Priority Queue Tutorial

Syntax

The syntax for list comprehension consists of three parts: the expression, the iteration, and the optional condition.

The expression is the value that will be included in the new list. The iteration defines the source list and the variable that represents each element in the source list. The condition, which is optional, is used to filter elements based on a specific criterion.

The general syntax for list comprehension is as follows:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
new_list = [expression for variable in source_list if condition]
new_list = [expression for variable in source_list if condition]
new_list = [expression for variable in source_list if condition]

Let's break down the syntax:

-

new_list
new_list: The new list that will be created.

-

expression
expression: The value or transformation that will be applied to each element in the source list.

-

variable
variable: The variable that represents each element in the source list.

-

source_list
source_list: The list from which elements will be selected.

-

if condition
if condition: The optional condition that filters elements based on a specific criterion.

Code Snippet

Let's consider an example where we have a list of numbers and we want to create a new list containing only the even numbers from the original list using list comprehension:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers)
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_numbers = [num for num in numbers if num % 2 == 0] print(even_numbers)
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers)

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
[2, 4, 6, 8, 10]
[2, 4, 6, 8, 10]
[2, 4, 6, 8, 10]

In this example, we use list comprehension to iterate over each number in the

numbers
numbers list. The condition
if num % 2 == 0
if num % 2 == 0 filters out the odd numbers, and the expression
num
num adds the even numbers to the
even_numbers
even_numbers list.

Using the Lambda Function for List Filtering

In addition to list comprehension, you can also use lambda functions to filter elements from a list. Lambda functions are anonymous functions that can be defined in a single line. They are commonly used with higher-order functions like

filter()
filter() and
map()
map().

Using lambda functions for list filtering can provide a more flexible and concise way to specify the filtering condition. It allows you to define the filtering logic inline without the need for a separate function definition.

Related Article: Tutorial: Django + MongoDB, ElasticSearch & Message Brokers

Syntax for the Lambda Function

The syntax for defining a lambda function is as follows:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
lambda arguments: expression
lambda arguments: expression
lambda arguments: expression

Let's break down the syntax:

-

lambda
lambda: The keyword used to define a lambda function.

-

arguments
arguments: The arguments that the lambda function takes.

-

expression
expression: The expression that is evaluated and returned by the lambda function.

Code Snippet for Lambda Function

Let's consider the same example as before, where we have a list of numbers and we want to filter out the even numbers using a lambda function with the

filter()
filter() function:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda num: num % 2 == 0, numbers))
print(even_numbers)
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_numbers = list(filter(lambda num: num % 2 == 0, numbers)) print(even_numbers)
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda num: num % 2 == 0, numbers))
print(even_numbers)

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
[2, 4, 6, 8, 10]
[2, 4, 6, 8, 10]
[2, 4, 6, 8, 10]

In this example, we use the

filter()
filter() function along with a lambda function to filter out the even numbers from the
numbers
numbers list. The lambda function
lambda num: num % 2 == 0
lambda num: num % 2 == 0 defines the filtering condition, and the
filter()
filter() function applies this condition to each element in the
numbers
numbers list.

The Filter Function

The

filter()
filter() function is a built-in function in Python that allows you to filter elements from a sequence based on a specific criterion. It takes two arguments: the filtering function and the sequence. The filtering function defines the condition for filtering, and the sequence is the source of the elements to be filtered.

The

filter()
filter() function returns an iterator that contains the filtered elements from the sequence. To obtain a list of the filtered elements, you can convert the iterator to a list using the
list()
list() function.

Applying Predicate with the Filter Function

In order to use the

filter()
filter() function, you need to define a filtering function or a lambda function that acts as a predicate. A predicate is a function that returns either
True
True or
False
False based on a given input.

The filtering function or lambda function should take an element from the sequence as input and return

True
True if the element satisfies the filtering condition, or
False
False otherwise.

Related Article: How to Determine the Length of an Array in Python

Code Snippet for the Filter Function

Let's consider the same example as before, where we have a list of numbers and we want to filter out the even numbers using the

filter()
filter() function:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def is_even(num):
return num % 2 == 0
even_numbers = list(filter(is_even, numbers))
print(even_numbers)
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] def is_even(num): return num % 2 == 0 even_numbers = list(filter(is_even, numbers)) print(even_numbers)
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

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

even_numbers = list(filter(is_even, numbers))
print(even_numbers)

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
[2, 4, 6, 8, 10]
[2, 4, 6, 8, 10]
[2, 4, 6, 8, 10]

In this example, we define the

is_even()
is_even() function as the filtering function. The function checks if a number is even by using the modulo operator
%
% to divide the number by 2 and checking if the remainder is 0. The
filter()
filter() function then applies the
is_even()
is_even() function to each element in the
numbers
numbers list and returns an iterator containing the even numbers. We convert the iterator to a list using the
list()
list() function to obtain the final result.

Additional Resources



- Python List Comprehension: The Complete Guide

- Understanding Python's lambda functions

- Python Filter() Function

You May Also Like

How to Use Reduction with Python

Reduction in Python involves various methods for simplifying and optimizing code. From minimization techniques to streamlining examples, this article… read more

Comparing Substrings in Python

This technical guide provides an overview of substring comparison in Python, covering various methods such as using index, slice, substring function,… read more

How to Force Pip to Reinstall the Current Version in Python

Guide to using pip for forcing reinstallation of the current Python version. This article provides step-by-step instructions on using the –force-rein… read more

How to Find Maximum and Minimum Values for Ints in Python

A simple guide to finding the maximum and minimum integer values in Python. Explore how to use the max() and min() functions, as well as some best pr… read more

How to Use Python Import Math GCD

This guide provides a concise overview of using the math.gcd function in Python. It covers how to import the math module, the purpose of the gcd func… read more

How to Use and Import Python Modules

Python modules are a fundamental aspect of code organization and reusability in Python programming. In this tutorial, you will learn how to use and i… read more

How to Use Pandas Dataframe Apply in Python

This article explores how to use the apply method in Python's Pandas library to apply functions to DataFrames. It covers the purpose and role of Data… read more

How To Filter Dataframe Rows Based On Column Values

Learn how to select rows from a dataframe based on their column values using Python's pandas library. Explore two methods, Boolean Indexing and the Q… read more

Working with List of Lists in Python (Nested Lists)

This guide provides an overview of working with list of lists in Python, including manipulation and access techniques. It covers topics such as neste… read more

How to Append to a Dict in Python

This article provides a guide on adding elements to a dictionary in Python. It covers an overview of Python dictionaries, key-value pairs, exploring … read more