Python filter()
Function
The filter() function in Python lets you filter elements from an iterable (like a list or tuple) based on a condition (a function that returns True or False).
This is useful when you want to keep only certain items from a collection.
Syntax
filter(function, iterable)
Parameters:
function
: A function that returnsTrue
orFalse
for each item.iterable
: The collection you want to filter (e.g. list, tuple, set).
Returns:
- An iterator with elements for which the function returned
True
.
Example 1: Filter Even Numbers
def is_even(n):
return n % 2 == 0
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(is_even, numbers)
print(list(even_numbers))
[2, 4, 6]
Example 2: Using Lambda with filter()
numbers = [10, 25, 30, 45, 50]
result = filter(lambda x: x > 30, numbers)
print(list(result))
[45, 50]
Use Case: Remove Empty Strings
names = ["Alice", "", "Bob", "", "Charlie"]
filtered_names = filter(None, names)
print(list(filtered_names))
['Alice', 'Bob', 'Charlie']
When None
is passed as the function, filter()
removes all "falsy" values (like ''
, 0
, None
).
How is filter()
Different from List Comprehension?
- filter() uses a function to decide which items to keep.
- List comprehension uses inline syntax.
# Using filter()
print(list(filter(lambda x: x > 0, [-2, 0, 3, 5]))) # [3, 5]
# Using list comprehension
print([x for x in [-2, 0, 3, 5] if x > 0]) # [3, 5]
Common Mistakes
- Forgetting to convert the result to a list:
list(filter(...))
- Not providing a valid function that returns True/False
- Passing a non-iterable as the second argument
Interview Tip
filter()
is often used in functional programming questions, especially when you need to reduce or process data streams efficiently without writing loops.
Summary
filter()
helps you pick elements that match a condition.- It returns an iterator, which you often convert to a list.
- Use with named functions or lambdas.
Practice Problem
Write a program that takes a list of numbers and filters out the negative ones.
nums = [-5, 3, -1, 0, 4, -2]
positive_nums = list(filter(lambda x: x >= 0, nums))
print(positive_nums)
Expected Output:
[3, 0, 4]