Open In App

filter() in python

Last Updated : 11 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not. Let's see a simple example of filter() function in python:

Example Usage of filter()

Python
# Function to check if a number is even
def even(n):
    return n % 2 == 0

a = [1, 2, 3, 4, 5, 6]
b = filter(even, a)

# Convert filter object to a list
print(list(b))  

Output
[2, 4, 6]

Explanation:

  • Function: even function checks if a number is divisible by 2.
  • Filter: The filter() applies this function to each item in numbers.
  • Result: A new iterable containing only even numbers is returned.

Let's explore filter() in detail:

Python filter() Syntax

The filter() method in Python has the following syntax:

Syntax: filter(function, sequence)

  • function: A function that defines the condition to filter the elements. This function should return True for items you want to keep and False for those you want to exclude.
  • iterable: The iterable you want to filter (e.g., list, tuple, set).

The result is a filter object, which can be converted into a list, tuple or another iterable type.

Let us see a few examples of the filter() function in Python.

Using filter() with lambda

For concise conditions, we can use a lambda function instead of defining a named function.

Python
a = [1, 2, 3, 4, 5, 6]
b = filter(lambda x: x % 2 == 0, a)

print(list(b))  

Output
[2, 4, 6]

Here, the lambda function replaces even and directly defines the condition x % 2 == 0 inline.

Combining filter() with Other Functions

We can combine filter() with other Python functions like map() or use it in a pipeline to process data efficiently.

Example: Filtering and Transforming Data

Python
a = [1, 2, 3, 4, 5, 6]

# First, filter even numbers
b = filter(lambda x: x % 2 == 0, a)

# Then, double the filtered numbers
c = map(lambda x: x * 2, b)

print(list(c))  

Output
[4, 8, 12]

Explanation:

  • The filter() function extracts even numbers from numbers.
  • The map() function doubles each filtered number.
  • The combination simplifies complex data pipelines.

Filter() Function in Python
Visit Course explore course icon
Video Thumbnail

Filter() Function in Python

Video Thumbnail

filter() in python

Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy