📝 Python

filter() — Pick What You Need!

P
Author
Pyland
📅
Published
03.04.2026
⏱️
Reading time
3 min
👁️
Views
224
🌿
Level
Medium

filter(None, data) removes all “falsy” values: None, False, 0, “”, [], {}.

What is filter()?

filter() selects elements for which the test function returns True.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Old way
even = []
for num in numbers:
    if num % 2 == 0:
        even.append(num)

# With filter()
even = list(filter(lambda x: x % 2 == 0, numbers))
print(even)  # [2, 4, 6, 8, 10]

Syntax

filter(predicate_function, iterable)
  • predicate_function — must return True / False
  • Returns a filter object — wrap it in list() to get a list

Basic Examples

Numbers

numbers = [5, 12, 3, 18, 25, 7]

# Above a threshold
above_10 = list(filter(lambda x: x > 10, numbers))
print(above_10)  # [12, 18, 25]

# Positive (with a named function)
def is_positive(x):
    return x > 0

mixed = [-5, 2, -3, 8, 0, -1, 10]
positive = list(filter(is_positive, mixed))
print(positive)  # [2, 8, 10]

Strings

words = ["python", "javascript", "go", "java", "typescript"]

# Contain "script"
with_script = list(filter(lambda w: "script" in w, words))
print(with_script)  # ['javascript', 'typescript']

# Start with "j"
starts_j = list(filter(lambda w: w.startswith("j"), words))
print(starts_j)  # ['javascript', 'java']

Dicts

students = [
    {"name": "Alice", "grade": 95},
    {"name": "Bob",   "grade": 67},
    {"name": "Carl",  "grade": 88},
    {"name": "Dave",  "grade": 72}
]

# Grade >= 80
high_performers = list(filter(lambda s: s["grade"] >= 80, students))
for s in high_performers:
    print(s["name"], s["grade"])
# Alice 95
# Carl 88

# Failed (< 70)
failed = list(filter(lambda s: s["grade"] < 70, students))
print([s["name"] for s in failed])  # ['Bob']

Multiple Conditions

numbers = [5, 12, 3, 18, 25, 7, 30]

# Even AND > 10
result = list(filter(lambda x: x % 2 == 0 and x > 10, numbers))
print(result)  # [12, 18, 30]

# < 10 OR > 20
result = list(filter(lambda x: x < 10 or x > 20, numbers))
print(result)  # [5, 3, 25, 7, 30]

Complex Example

products = [
    {"name": "Phone",   "price": 500,  "in_stock": True},
    {"name": "Laptop",  "price": 1200, "in_stock": False},
    {"name": "Mouse",   "price": 25,   "in_stock": True},
    {"name": "Monitor", "price": 300,  "in_stock": True}
]

# In stock AND price < 600
affordable = list(filter(
    lambda p: p["in_stock"] and p["price"] < 600,
    products
))

for p in affordable:
    print(f"{p['name']}: ${p['price']}")
# Phone: $500
# Mouse: $25
# Monitor: $300

filter() vs List Comprehension

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# filter()
even_filter = list(filter(lambda x: x % 2 == 0, numbers))

# List comprehension
even_comp = [x for x in numbers if x % 2 == 0]

print(even_filter == even_comp)  # True

filter() is convenient when a ready-made predicate function already exists:

def is_adult(person):
    return person["age"] >= 18

adults = list(filter(is_adult, people))

Comprehension is better when you need to filter and transform at the same time:

adult_names = [p["name"] for p in people if p["age"] >= 18]

Common Mistakes

Mistake 1: Forgot list()

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

result = filter(lambda x: x > 2, numbers)
print(result)  # <filter object at 0x...>  — not a list!

# ✅ CORRECT
result = list(filter(lambda x: x > 2, numbers))
print(result)  # [3, 4, 5]

Mistake 2: filter(None) removes 0

data = [0, 5, 10, 15]

# filter(None) will remove 0!
result = list(filter(None, data))
print(result)  # [5, 10, 15]  ← 0 is gone

# If 0 is a valid value:
result = list(filter(lambda x: x is not None, data))
print(result)  # [0, 5, 10, 15]

filter(None, data) removes all “falsy” values: None, False, 0, "", [], {}.


filter() + map()

Filter first, then transform:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Even → double
result = list(map(lambda x: x * 2, filter(lambda x: x % 2 == 0, numbers)))
print(result)  # [4, 8, 12, 16, 20]

# Same with comprehension
result = [x * 2 for x in numbers if x % 2 == 0]
print(result)  # [4, 8, 12, 16, 20]

Your reaction to the article

💬 Comments (0)

🔐 Sign in to leave a comment
🚪 Login
💭

No comments yet

Be the first to share your opinion about this article!

🔗 Similar

Similar articles

Continue learning with these materials

📝

Event Loop in Python: How asyncio Achieves "Paral…

Event loop is the heart of asyncio. It doesn't run code in parallel across multiple...

📅 30.06.2026 👁️ 135
📝

pytest-django: Testing Django

Охватываемые темы: Installation, @pytest.mark.djangodb, Fixtures, Testing views.

📅 30.06.2026 👁️ 144
📝

pip: Python Package Manager

Охватываемые темы: Installing packages, Upgrading and removing, requirements.txt, Virtual environment.

📅 30.06.2026 👁️ 139

Did you like the article?

Subscribe to our updates and receive new articles first. Grow with PyLand!