Tutorial

How To Use the Python Filter Function

Compact guide to the python filter function: syntax, return type (filter object), examples with lambda, None, lists of dictionaries, and best practices.

Drake Nguyen

Founder · System Architect

3 min read
How To Use the Python Filter Function
How To Use the Python Filter Function

Introduction

The python filter function is a compact, built-in utility for creating a new iterator that yields only the items from an iterable which satisfy a given test. The filter() python built-in functions filter accepts a callable and an iterable, evaluates each element with the callable (the predicate), and returns a filter object — an iterator that produces the filtered results on demand.

Because filter() returns an iterator rather than creating a brand-new list immediately, it can be more memory-efficient than creating a full list with a list comprehension when working with large datasets. Below you’ll find several practical python filter examples showing how to use filter() in python for common tasks, including with lambda, with None, and with more complex structures like lists of dictionaries.

Syntax and return type

Basic syntax:

filter(function, iterable)

The result is a filter object — an iterator. To materialize the values into a list, call:

list(filter(...))

Use keywords: python filter function, filter() python, python filter object to list, python filter function return type filter object.

Using filter() with a function

You can pass a normal function as the first argument. The function (predicate) should return a truthy value for items you want to keep and a falsy value for items you want removed.

Example: keep even numbers

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

numbers = [1, 2, 3, 4, 5, 6]
filtered = filter(is_even, numbers)      # filtered is a filter object (iterator)
print(list(filtered))                    # [2, 4, 6]

This example demonstrates the predicate approach and highlights that filter returns an iterator rather than a list immediately. Keywords used: python filter examples, filter object, iterator.

Using filter() with lambda

For short predicates, a lambda function keeps your code concise. This is common when using python filter lambda for inline tests.

Example: strings starting with a vowel

names = ['Sammy', 'Ashley', 'Jo', 'Olly', 'Jackie', 'Charlie']
starts_with_vowel = list(filter(lambda s: s[0].lower() in 'aeiou', names))
print(starts_with_vowel)  # ['Ashley', 'Olly']

Compare filter vs list comprehension: both can produce the same output, e.g. [s for s in names if s[0].lower() in 'aeiou'], but filter can be preferable when you want an iterator or when you already have a predicate function. Keywords: python filter lambda, python filter list, python filter vs list comprehension.

Using None with filter()

Passing None as the function causes filter() to remove items that are considered falsy (empty sequences, zero, False, None). This is useful for quickly cleaning data.

Example: remove falsy values

items = [11, False, 18, 21, '', 12, 34, 0, [], {}]
clean = list(filter(None, items))
print(clean)  # [11, 18, 21, 12, 34]

This is often more readable than a comprehension when the goal is to drop falsy values. Keyword: python filter none, python filter function with None example.

Filter with a list of dictionaries

When an iterable contains dictionaries you can write a predicate that inspects each dictionary’s values or keys. A nested function or a lambda (if simple) works well.

Example: search across dictionary values

creatures = [
    {'name': 'sammy',  'species': 'shark',     'tank': '11', 'type': 'fish'},
    {'name': 'ashley', 'species': 'crab',      'tank': '25', 'type': 'shellfish'},
    {'name': 'jo',     'species': 'guppy',     'tank': '18', 'type': 'fish'},
    {'name': 'jackie', 'species': 'lobster',   'tank': '21', 'type': 'shellfish'},
    {'name': 'charlie','species': 'clownfish', 'tank': '12', 'type': 'fish'},
    {'name': 'olly',   'species': 'green turtle','tank': '34','type': 'turtle'}
]

def contains_search(obj, term):
    for v in obj.values():
        if term in str(v):
            return True
    return False

result = list(filter(lambda d: contains_search(d, '2'), creatures))
print(result)  # dictionaries whose values contain '2'

Keywords: python filter list of dictionaries, python filter list of dictionaries example. This pattern scales to more complex predicates and is useful when implementing search filters over records.

Best practices and considerations

  • Remember filter() returns an iterator; convert with list() if you need random access or multiple passes. (convert filter object to list python)
  • For very simple tests, lambda + filter() keeps code compact. For complex logic, define a named function for readability and testability. (python filter lambda examples for beginners)
  • When working with large streams, prefer the iterator behavior of filter() to reduce memory usage compared to always materializing lists. (python filter function return iterator)
  • If you’re already using list comprehensions extensively, choose whichever style improves clarity for your team; they often perform similarly for moderate-sized data. (python filter vs list comprehension)

Conclusion

The python filter function is a small but powerful tool for functional-style filtering. Whether you use a named predicate, a lambda function, or None to drop falsy values, filter() helps you build memory-efficient pipelines and concise filters. Try the examples above and adapt them to your datasets — for instance, converting the resulting filter object to a list when you need to examine all matches at once.

Further reading: explore map and filter to learn more about functional programming in python and how built-in functions interplay with iterators and generators.

Stay updated with Netalith

Get coding resources, product updates, and special offers directly in your inbox.