0
0
Pythonprogramming~5 mins

filter() function in Python

Choose your learning style9 modes available
Introduction

The filter() function helps you pick items from a list (or other collections) that match a rule you set. It keeps only the items you want.

When you want to get only even numbers from a list of numbers.
When you need to find all words longer than 5 letters in a list of words.
When you want to remove empty strings from a list of text.
When you want to select only active users from a list of user data.
Syntax
Python
filter(function, iterable)

function is a rule that returns True or False for each item.

iterable is the list or collection you want to filter.

Examples
Filters even numbers from the list.
Python
filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5])
Filters words longer than 5 letters using a named function.
Python
def is_long(word):
    return len(word) > 5

filter(is_long, ['apple', 'banana', 'pear'])
Filters out empty strings by using None as the function.
Python
filter(None, ['apple', '', 'banana', '', 'pear'])
Sample Program

This program keeps numbers greater than 18 from the list and prints them.

Python
numbers = [10, 15, 20, 25, 30]
# Keep only numbers greater than 18
filtered_numbers = filter(lambda x: x > 18, numbers)

# Convert filter object to list to print
result = list(filtered_numbers)
print(result)
OutputSuccess
Important Notes

filter() returns a filter object, so you often convert it to a list to see the results.

If you use None as the function, filter() removes items that are false-like (e.g., empty strings, zero, None).

Summary

filter() helps pick items from a collection based on a rule.

You give it a function that returns True or False for each item.

The result is a filtered collection with only the items that passed the rule.