Python

Python filter() Function

The filter() function is a built-in Python function used to select items from an iterable based on a condition.

Unlike map(), which transforms every item, filter() keeps only the items for which the condition returns True.

Basic Syntax

filter(function, iterable)

For example:

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

Output:

[3, 4, 5]

Here:

  • filter() → selects items based on a condition
  • lambda x: x > 2 → condition applied to each item
  • numbers → iterable being processed
  • list() → converts the filter result into a list

Important: filter() returns a filter object, not a list directly.

1. Basic filter() Example

Let's select even numbers from a list.

numbers = [1, 2, 3, 4, 5, 6]
result = filter(
    lambda x: x % 2 == 0,
    numbers
)
print(list(result))

Output:

[2, 4, 6]

The condition:

x % 2 == 0

returns True for even numbers.

The filtering process is:

1 → False

2 → True

3 → False

4 → True

5 → False

6 → True

Therefore:

[2, 4, 6]

2. filter() with a Normal Function

filter() does not require a lambda function. We can pass a normal function as well.

def is_even(number):
    return number % 2 == 0
numbers = [1, 2, 3, 4, 5, 6]
result = filter(is_even, numbers)
print(list(result))

Output:

[2, 4, 6]

This approach is useful when the condition is complex or needs to be reused.

3. filter() with Lambda

For short conditions, lambda functions are convenient.

numbers = [10, 15, 20, 25, 30]
result = filter(
    lambda x: x > 20,
    numbers
)
print(list(result))

Output:

[25, 30]

The lambda function:

lambda x: x > 20

checks every number and keeps only numbers greater than 20.

4. Filter Odd Numbers

We can select odd numbers using:

numbers = [1, 2, 3, 4, 5, 6, 7, 8]
result = filter(
    lambda x: x % 2 != 0,
    numbers
)
print(list(result))

Output:

[1, 3, 5, 7]

5. Filter Numbers Greater Than 50

numbers = [20, 45, 60, 75, 30, 90]
result = filter(
    lambda x: x > 50,
    numbers
)
print(list(result))

Output:

[60, 75, 90]

6. Filter Numbers Less Than 50

numbers = [20, 45, 60, 75, 30, 90]
result = filter(
    lambda x: x < 50,
    numbers
)
print(list(result))

Output:

[20, 45, 30]

7. Filter Positive Numbers

numbers = [-5, 10, -3, 20, 0, -8, 15]
positive = filter(
    lambda x: x > 0,
    numbers
)
print(list(positive))

Output:

[10, 20, 15]

8. Filter Negative Numbers

numbers = [-5, 10, -3, 20, 0, -8, 15]
negative = filter(
    lambda x: x < 0,
    numbers
)
print(list(negative))

Output:

[-5, -3, -8]

9. Filter Strings by Length

filter() can also be used with strings.

names = ["Ram", "Sita", "Hari", "Raj", "Anita"]
result = filter(
    lambda name: len(name) > 3,
    names
)
print(list(result))

Output:

['Sita', 'Hari', 'Anita']

Only names containing more than three characters are selected.

10. Filter Names Starting With a Specific Letter

We can use the startswith() string method.

names = ["Ram", "Raj", "Sita", "Ramesh", "Hari"]
result = filter(
    lambda name: name.startswith("R"),
    names
)
print(list(result))

Output:

['Ram', 'Raj', 'Ramesh']

11. Filter Names Ending With a Specific Letter

names = ["Ram", "Sita", "Hari", "Gita", "Raj"]
result = filter(
    lambda name: name.endswith("a"),
    names
)
print(list(result))

Output:

['Sita', 'Gita']

 

12. filter() with Tuples

filter() can process tuples too.

numbers = (10, 15, 20, 25, 30)
result = filter(
    lambda x: x % 2 == 0,
    numbers
)
print(tuple(result))

Output:

(10, 20, 30)

 

Notice that we use:

tuple(result)

to convert the result back into a tuple.

13. filter() with Sets

We can also use filter() with sets.

numbers = {10, 15, 20, 25, 30}
result = filter(
    lambda x: x > 20,
    numbers
)
print(set(result))

Possible output:

{25, 30}

Remember that sets are unordered collections, so their display order can vary.

14. Filter Students Based on Marks

Suppose we have student marks:

marks = [45, 78, 32, 90, 65, 28, 88]

We want students who passed.

passed = filter(
    lambda mark: mark >= 40,
    marks
)
print(list(passed))

Output:

[45, 78, 90, 65, 88]

The condition is:

mark >= 40

So marks below 40 are removed.

15. Filter Students Who Scored Distinction

marks = [45, 78, 32, 90, 65, 28, 88]
distinction = filter(
    lambda mark: mark >= 80,
    marks
)
print(list(distinction))

Output:

[90, 88]

16. Filter Employees Based on Salary

salaries = [25000, 40000, 55000, 30000, 75000]
result = filter(
    lambda salary: salary >= 50000,
    salaries
)
print(list(result))

Output:

[55000, 75000]

This type of filtering is useful when working with employee or financial data.

17. filter() with Dictionary Data

Consider the following dictionary:

students = {
    "Ram": 75,
    "Sita": 85,
    "Hari": 35,
    "Gita": 90
}

We want students who scored at least 80.

result = filter(
    lambda item: item[1] >= 80,
    students.items()
)
print(list(result))

Output:

[('Sita', 85), ('Gita', 90)]

Each item from:

students.items()

looks like:

("Ram", 75)

Therefore:

item[0]

contains the student's name.

And:

item[1]

contains the student's marks.

18. Convert Filtered Dictionary Data Back to a Dictionary

We can convert the filtered result into a dictionary.

students = {
    "Ram": 75,
    "Sita": 85,
    "Hari": 35,
    "Gita": 90
}
result = filter(
    lambda item: item[1] >= 80,
    students.items()
)
top_students = dict(result)
print(top_students)

Output:

{'Sita': 85, 'Gita': 90}

19. filter() Without a Function

The first argument of filter() can be None.

values = [0, 1, False, True, "", "Python", None, 10]
result = filter(None, values)
print(list(result))

Output:

[1, True, 'Python', 10]

When the function is None, filter() removes falsy values.

Common falsy values include:

False

0

0.0

""

None

Truthy values include:

True

1

"Python"

[1, 2, 3]

20. Multiple Conditions Using and

We can use multiple conditions.

numbers = [10, 15, 20, 25, 30, 35, 40]
result = filter(
    lambda x: x > 20 and x % 2 == 0,
    numbers
)
print(list(result))

Output:

[30, 40]

The number must satisfy both conditions:

number > 20

AND

number is even

21. Multiple Conditions Using or

We can also use or.
numbers = [10, 15, 20, 25, 30, 35]
result = filter(
    lambda x: x < 15 or x > 30,
    numbers
)
print(list(result))

Output:

[10, 35]

The number is selected if either condition is True.

22. filter() with Dictionary/List of Objects

This is a very common real-world situation.

Suppose we have products:

products = [
    {"name": "Laptop", "price": 80000},
    {"name": "Mouse", "price": 1500},
    {"name": "Keyboard", "price": 3000},
    {"name": "Monitor", "price": 25000}
]

We want products costing more than 20,000.

expensive_products = filter(
    lambda product: product["price"] > 20000,
    products
)
print(list(expensive_products))

Output:

[
    {'name': 'Laptop', 'price': 80000},
    {'name': 'Monitor', 'price': 25000}
]

This is particularly useful when filtering data received from an API or database.

23. Practical Example : Filter Adult Ages

We can create a reusable function:

def is_adult(age):
    return age >= 18
ages = [12, 17, 18, 21, 15, 25]
adults = filter(
    is_adult,
    ages
)
print(list(adults))

Output:

[18, 21, 25]

24. filter() Returns a Filter Object

Consider:

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

The output will look similar to:

<filter object at 0x...>

This happens because filter() returns a filter object, not a normal list.

To see the actual values:

print(list(result))

Output:

[3, 4, 5]

25. filter() Is Lazy

filter() uses lazy evaluation.

It does not need to create a complete list of filtered values immediately.

For example:

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

Output:

3
4
5

The values are produced as they are requested.

This can be useful when working with large amounts of data.

26. filter() with a for Loop

A filter object can be directly used in a loop.

numbers = [1, 2, 3, 4, 5, 6]
result = filter(
    lambda x: x % 2 == 0,
    numbers
)
for value in result:
    print(value)

Output:

2
4
6

There is no need to convert the result to a list when you simply want to iterate over it.

27. Practical Example : Budget Products

products = [
    {"name": "Laptop", "price": 80000},
    {"name": "Mouse", "price": 1500},
    {"name": "Keyboard", "price": 3000},
    {"name": "Monitor", "price": 25000}
]
budget_products = filter(
    lambda product: product["price"] <= 25000,
    products
)
for product in budget_products:
    print(product)

Output:

{'name': 'Mouse', 'price': 1500}
{'name': 'Keyboard', 'price': 3000}
{'name': 'Monitor', 'price': 25000}

28. map() vs filter()

This distinction is very important.

map()

map() is used to transform every item.

numbers = [1, 2, 3, 4]
result = map(
    lambda x: x * 2,
    numbers
)
print(list(result))

Output:

[2, 4, 6, 8]

Every item is transformed.

filter()

filter() is used to select items.

numbers = [1, 2, 3, 4]
result = filter(
    lambda x: x % 2 == 0,
    numbers
)
print(list(result))

Output:

[2, 4]

Only matching items are selected.

Remember

map()     → Transform

filter()  → Select

29. filter() vs List Comprehension

The same filtering operation can also be performed using list comprehension.

Using filter()

numbers = [1, 2, 3, 4, 5, 6]
result = filter(
    lambda x: x % 2 == 0,
    numbers
)
print(list(result))

Using List Comprehension

numbers = [1, 2, 3, 4, 5, 6]
result = [
    x for x in numbers
    if x % 2 == 0
]
print(result)

Both produce:

[2, 4, 6]

List comprehensions are often easier to read for simple filtering, while filter() is useful when working with functions and functional-style programming.

30. Practical Example : Student Result Filtering

students = [
    {"name": "Raj", "marks": 85},
    {"name": "John", "marks": 35},
    {"name": "Sita", "marks": 91},
    {"name": "Hari", "marks": 42}
]
passed_students = filter(
    lambda student: student["marks"] >= 40,
    students
)
for student in passed_students:
    print(student)

Output:

{'name': 'Raj', 'marks': 85}
{'name': 'Sita', 'marks': 91}
{'name': 'Hari', 'marks': 42}

This example shows how filter() can be used to process structured data.

Important Points to Remember

  1. filter() is used to select data.
  2. It works with iterables such as lists, tuples, sets, and dictionaries.
  3. The filtering function should return True or False.
  4. Lambda functions are commonly used with filter().
  5. filter() returns a filter object.
  6. Use list() when you need the filtered values as a list.
  7. filter() does not modify the original iterable.
  8. filter() supports multiple conditions.
  9. filter(None, iterable) removes falsy values.
  10. filter() uses lazy evaluation.

The basic pattern to remember is:

filter(condition, iterable)

For example:

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

Output:

[2, 4, 6]
Interactive Sandbox
Python