Notes

`filter()` Function in Python [ English ]

< Prev Next >

1. Introduction

The filter() function in Python is a built-in function used to select elements from an iterable based on a specified condition. It applies a function to each element of an iterable and returns only those elements for which the function returns True.

In simple terms, filter() is used to remove unwanted elements from a sequence according to a condition.

The function returns a filter object (iterator) containing the filtered elements.

2. Syntax

filter(function, iterable)

Parameters

  1. function A function that tests each element and returns either True or False.

  2. iterable A sequence such as a list, tuple, or string whose elements are to be filtered.

Return Value

3. Basic Example

def even_number(n):
    return n % 2 == 0

numbers = [1, 2, 3, 4, 5, 6]

result = filter(even_number, numbers)

print(list(result))

Output

[2, 4, 6]

Explanation

4. Using filter() with a Lambda Function

A lambda function can be used for short conditions.

numbers = [1, 2, 3, 4, 5, 6]

result = filter(lambda x: x % 2 == 0, numbers)

print(list(result))

Output

[2, 4, 6]

Explanation

5. Example: Filtering Positive Numbers

numbers = [-5, 3, -2, 7, -1, 10]

result = filter(lambda x: x > 0, numbers)

print(list(result))

Output

[3, 7, 10]

Explanation

6. Example with Strings

words = ["apple", "", "banana", "", "cherry"]

result = filter(None, words)

print(list(result))

Output

['apple', 'banana', 'cherry']

Explanation

7. Without filter() vs With filter()

Without filter()

numbers = [1, 2, 3, 4, 5]
result = []

for n in numbers:
    if n % 2 == 0:
        result.append(n)

print(result)

With filter()

numbers = [1, 2, 3, 4, 5]

result = filter(lambda x: x % 2 == 0, numbers)

print(list(result))

Advantage

8. Important Points

Example:

result = filter(lambda x: x > 3, [1, 2, 3, 4, 5])
print(list(result))

Output:

[4, 5]

9. Summary

< Prev Next >