Python Basics — filter() Function
The filter() Function
filter() selects items from an iterable that satisfy a condition. It returns an iterator containing only the items for which the function returns True.
Syntax
filter(function, iterable)
function— a function that returnsTrueorFalsefor each itemiterable— the data to filter
Basic Usage
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Keep only even numbers
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4, 6, 8, 10]
Filtering with Named Functions
def is_positive(n):
return n > 0
values = [-5, -2, 0, 3, 7, -1, 8]
positive = list(filter(is_positive, values))
print(positive) # [3, 7, 8]
Filtering with Lambda
# Words longer than 4 characters
words = ["hi", "hello", "hey", "greetings", "yo", "welcome"]
long_words = list(filter(lambda w: len(w) > 4, words))
print(long_words) # ['hello', 'greetings', 'welcome']
# Ages of adults (18+)
ages = [12, 18, 25, 8, 30, 15, 22]
adults = list(filter(lambda age: age >= 18, ages))
print(adults) # [18, 25, 30, 22]
Removing Falsy Values — filter(None, iterable)
When you pass None as the function, filter removes all falsy values:
data = [0, 1, "", "hello", None, True, False, [], [1, 2], {}, {"a": 1}]
truthy = list(filter(None, data))
print(truthy) # [1, 'hello', True, [1, 2], {'a': 1}]
Falsy values in Python: 0, "", None, False, [], (), {}, set().
Practical Use: Cleaning Data
# Remove empty strings from user input
raw_inputs = ["Alice", "", "Bob", " ", "", "Charlie"]
non_empty = list(filter(lambda s: s.strip(), raw_inputs))
print(non_empty) # ['Alice', 'Bob', ' ', 'Charlie']
# Using None — removes only empty strings, not whitespace-only
non_empty = list(filter(None, raw_inputs))
print(non_empty) # ['Alice', 'Bob', ' ', 'Charlie']
filter() vs List Comprehension
| Feature | filter() |
List Comprehension |
|---|---|---|
| Syntax | filter(func, iterable) |
[x for x in iterable if cond] |
| Returns | Iterator (lazy) | List (eager) |
| Transform + filter | Needs map() too |
Both in one expression |
| Readability | Good with existing functions | Better for most cases |
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# filter()
evens = list(filter(lambda x: x % 2 == 0, numbers))
# List comprehension — more Pythonic
evens = [x for x in numbers if x % 2 == 0]
print(evens) # [2, 4, 6, 8, 10]
# Combined filter + transform: squares of even numbers
# filter + map
result1 = list(map(lambda x: x**2, filter(lambda x: x % 2 == 0, numbers)))
# List comprehension — much cleaner
result2 = [x**2 for x in numbers if x % 2 == 0]
print(result1) # [4, 16, 36, 64, 100]
print(result2) # [4, 16, 36, 64, 100]
filterfalse() from itertools
The opposite of filter() — keeps items where the function returns False:
from itertools import filterfalse
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Keep odd numbers (where is_even returns False)
odds = list(filterfalse(lambda x: x % 2 == 0, numbers))
print(odds) # [1, 3, 5, 7, 9]
Splitting Data with filter + filterfalse
from itertools import filterfalse
def is_passing(score):
return score >= 60
scores = [45, 72, 88, 55, 90, 38, 65]
passed = list(filter(is_passing, scores))
failed = list(filterfalse(is_passing, scores))
print(f"Passed: {passed}") # Passed: [72, 88, 90, 65]
print(f"Failed: {failed}") # Failed: [45, 55, 38]
Practical Examples
Filtering Dictionaries
products = [
{"name": "Laptop", "price": 75000, "in_stock": True},
{"name": "Mouse", "price": 500, "in_stock": False},
{"name": "Keyboard", "price": 2000, "in_stock": True},
{"name": "Monitor", "price": 25000, "in_stock": True},
]
# In-stock products under 30000
affordable = list(filter(
lambda p: p["in_stock"] and p["price"] < 30000,
products
))
for p in affordable:
print(f"{p['name']}: ₹{p['price']}")
# Keyboard: ₹2000
# Monitor: ₹25000
Filtering with Multiple Conditions
students = [
{"name": "Alice", "gpa": 3.8, "year": 3},
{"name": "Bob", "gpa": 2.5, "year": 4},
{"name": "Charlie", "gpa": 3.9, "year": 2},
{"name": "Diana", "gpa": 3.5, "year": 4},
]
# Seniors with GPA > 3.0
honor_roll = list(filter(
lambda s: s["year"] == 4 and s["gpa"] > 3.0,
students
))
print([s["name"] for s in honor_roll]) # ['Diana']
Summary
filter(func, iterable)keeps items wherefuncreturnsTrue- Returns an iterator — wrap in
list()to see results filter(None, iterable)removes falsy valuesfilterfalse()from itertools keeps where function returnsFalse- Prefer list comprehensions for most filtering in Python
- Use
filter()when passing an existing predicate function
Next up: reduce() Function →