PYTHON

Python filter(): Syntax, Usage, and Examples

You can use the filter() function in Python to extract elements from a sequence that meet a certain condition. Instead of writing a full loop with if statements, the Python filter() function lets you express filtering logic in a clear and concise way. It returns only those values for which a given function returns True.

As a built-in function, filter() is available in all Python installations without requiring any imports, making it accessible for beginners learning Python. Unlike JavaScript, which uses array methods like .filter(), Python's approach allows you to filter any iterable using conditional statements in a more functional style.

This function comes in handy when you're working with lists, arrays, or dictionaries and want to clean up or reduce data without mutating the original structure. It's particularly useful when working with various data structures in Python.

Quick Answer: How to Use the filter() Function in Python

The built-in filter() function creates an iterator from an iterable (like a list) by keeping only the items for which a given function returns True. It provides a clean, functional way to select a subset of data.

Syntax:filter(function, iterable)

The result is a filter object, so you typically wrap it with list() to see the results immediately.

Example:

# A list of numbers
ages = [12, 17, 21, 30, 15]

# Define a function that returns True for adults
def is_adult(age):
    return age >= 18

# Use filter() to get only the adult ages
adults_iterator = filter(is_adult, ages)

# Convert the iterator to a list to view it
adults_list = list(adults_iterator)

print(adults_list)
# Outputs: [21, 30]

For simple, one-time checks, it's common to use a lambda function:

adults = list(filter(lambda age: age >= 18, ages))
print(adults)
# Outputs: [21, 30]

How filter() Works in Python

The basic syntax is:

filter(function, iterable)
  • function: A callable that accepts one argument and returns True or False.
  • iterable: Any iterable object like a list, tuple, set, or dictionary.

The result is a filter object—an iterator—which you can convert to a list or another iterable if needed. The return value of filter() is not a list but an iterator object, which can be converted to various collection types.

Example

def is_positive(num):
    return num > 0

numbers = [-3, -1, 0, 2, 5]
filtered = filter(is_positive, numbers)
print(list(filtered))  # Output: [2, 5]

You can also use a lambda function instead of defining a named one:

print(list(filter(lambda x: x > 0, numbers)))

A common function used with filter() is is_even, which checks if a number is even:


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

# Any number that is not even will **return False**

Why Use filter() in Python

You should reach for filter() when you want to streamline conditional selection. It's especially useful for:

  • Keeping only valid data entries from a list or array
  • Applying business rules to datasets
  • Filtering user input or API responses
  • Simplifying logic in functional pipelines

Instead of managing temporary lists and for loops manually, you express your filtering logic in one line. This approach is similar to filtering in other languages like Java or SQL, but with Python's more concise syntax.

Practical Examples

Remove Empty Strings from a List

values = ["apple", "", "banana", "", "cherry"]
cleaned = list(filter(None, values))
print(cleaned)  # Output: ['apple', 'banana', 'cherry']

Passing None as the function filters out all falsy values, including "", 0, False, and None.

Filter a List with a Condition

ages = [12, 17, 21, 30, 15]
adults = list(filter(lambda age: age >= 18, ages))
print(adults)  # Output: [21, 30]

This example reads almost like plain English: keep only the ages that are 18 or older.

Filter a Dictionary by Value

scores = {"Alice": 85, "Bob": 42, "Cleo": 91}
passed = dict(filter(lambda item: item[1] >= 60, scores.items()))
print(passed)  # Output: {'Alice': 85, 'Cleo': 91}

Using filter() with .items() makes it easy to work with dictionaries.

Filter for Even Numbers

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)# Output: [2, 4, 6, 8, 10]

This is a classic example of filtering a list of numbers to extract only the even numbers.

Filter Custom Objects

class Task:
    def __init__(self, title, done):
        self.title = title
        self.done = done

tasks = [
    Task("Write report", True),
    Task("Test code", False),
    Task("Send email", True)
]

completed = list(filter(lambda task: task.done, tasks))
for task in completed:
    print(task.title)  # Output: Write report, Send email

This pattern works great for task managers or any object-based application.

Combining filter() with Other Tools

Use map() and filter() Together

You can pair filtering and transformation in a single pipeline:

numbers = [1, 2, 3, 4, 5, 6]
squares_of_even = list(map(lambda x: x**2, filter(lambda x: x % 2 == 0, numbers)))
print(squares_of_even)  # Output: [4, 16, 36]

First, the list gets filtered, then each remaining item is squared. This approach works well in Python 3, which treats these functions as returning iterators for better memory efficiency.

List Comprehension vs. filter()

You can achieve the same result with list comprehension:

[x for x in numbers if x % 2 == 0]

Use filter() when the function is reusable or comes from another part of your program. Prefer comprehensions for simpler, more inline logic.

Filtering in Common Scenarios

Filter Input Data

raw_input = ["", "email@example.com", None, "admin@site.com"]
valid = list(filter(lambda x: x, raw_input))

This quickly removes blanks or null entries before saving or processing.

Filter from External Sources

When parsing data from APIs or user uploads, filter() gives you an easy first-pass cleanup:

records = [{"id": 1}, {}, {"id": 2}]
valid_records = list(filter(lambda r: "id" in r, records))

This ensures only entries with required fields stay in the list.

Create Your Own Filtering Function

def is_uppercase(word):
    return word.isupper()

words = ["YES", "no", "MAYBE", "sure"]
result = list(filter(is_uppercase, words))

You can apply any condition you want, as long as your function returns a boolean.

Considerations When Using filter() in Python

  • filter() returns an iterator. If you need to reuse the results, convert it to a list right away.
  • Avoid overusing it for complex logic. If your condition spans more than one line, use a regular for loop instead.
  • Don’t mix filtering and side effects. Keep your filtering functions pure—no printing, writing to files, or modifying global variables.
  • For clarity, you can assign the result to a descriptive variable like filtered_list to make your code more readable.

Related Use Cases

Filtering Arrays (Python Array Filter)

You can use filter() on arrays created from the array module:

import array
data = array.array("i", [1, -2, 3, -4])
positives = list(filter(lambda x: x > 0, data))

Works just like with lists, as long as the iterable is compatible.

Filtering with lambda (Lambda Python Filter)

Using lambda functions is a common way to define one-off filters inline. Just make sure your lambda stays readable. For anything complex, break it into a named function.

Filtering in Data Analysis

While Python’s built-in filter() is useful, libraries like pandas offer even more powerful filtering options. Still, mastering the core filter() function helps you build solid foundations before moving to more advanced tools. Many Python tutorial resources recommend understanding filter() as it applies to various data types.

The Python filter() function gives you a clean, expressive way to extract specific data from any iterable. By using it effectively, you can write code that reads well, performs reliably, and handles common data-processing patterns with ease. When paired with functions, lambdas, or tools like map(), it becomes a key part of your Python programming toolbox.

Key Takeaways for Python filter()

  • It Returns an Iterator: filter() does not return a list directly. It returns an iterator object, which is memory-efficient. You must use list(), tuple(), or another constructor to see the results.
  • It Needs a Function: The first argument to filter() must be a function (or a lambda) that takes one item as an input and returns True or False.
  • Keeps Items that are True: The new collection will only contain items for which the function returned True.
  • Does Not Change the Original: filter() is a non-destructive operation; the original iterable you passed to it remains unchanged.
  • Use None for Truthiness: Passing None as the function (filter(None, my_list)) is a shortcut to remove all "falsy" values from an iterable (e.g., 0, "", False, None).
Learn to Code in Python for Free
Start learning now
button icon
To advance beyond this tutorial and learn Python by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2025 Mimo GmbH

Reach your coding goals faster