0
0
PythonHow-ToBeginner · 3 min read

How to Use Filter Function in Python: Syntax and Examples

The filter() function in Python lets you select items from a list (or any iterable) that meet a condition defined by a function. It takes two arguments: a function that returns True or False, and an iterable, returning an iterator with only the items where the function returns True.
📐

Syntax

The filter() function has this syntax:

  • filter(function, iterable)

function: A function that takes one item and returns True or False.

iterable: A list, tuple, or any collection to filter.

The result is an iterator with items where the function returned True.

python
filter(function, iterable)
💻

Example

This example filters a list of numbers to keep only even numbers.

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

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

filtered_numbers = filter(is_even, numbers)

print(list(filtered_numbers))
Output
[2, 4, 6]
⚠️

Common Pitfalls

One common mistake is forgetting that filter() returns an iterator, not a list. You often need to convert it to a list with list() to see the results.

Another mistake is passing None as the function, which filters out items that are falsey (like 0, '', or False).

python
numbers = [0, 1, 2, 3]

# Wrong: printing filter object directly
print(filter(lambda x: x > 1, numbers))  # Shows filter object, not values

# Right: convert to list
print(list(filter(lambda x: x > 1, numbers)))  # Shows filtered values
Output
<filter object at 0x7f...> [2, 3]
📊

Quick Reference

  • filter(function, iterable): Returns an iterator with items where function(item) is True.
  • Use list() to convert the result to a list.
  • If function is None, filters out falsey values.

Key Takeaways

Use filter() to select items from an iterable based on a condition function.
Remember to convert the filter result to a list to see the filtered items.
Passing None as the function filters out falsey values automatically.
The function passed to filter() must return True or False for each item.
Filter works with any iterable, not just lists.