The filter() function helps you pick items from a list (or other collections) that match a rule you set. It keeps only the items you want.
filter() function in Python
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Python
filter(function, iterable)function is a rule that returns True or False for each item.
iterable is the list or collection you want to filter.
Examples
Python
filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5])
Python
def is_long(word): return len(word) > 5 filter(is_long, ['apple', 'banana', 'pear'])
None as the function.Python
filter(None, ['apple', '', 'banana', '', 'pear'])
Sample Program
This program keeps numbers greater than 18 from the list and prints them.
Python
numbers = [10, 15, 20, 25, 30] # Keep only numbers greater than 18 filtered_numbers = filter(lambda x: x > 18, numbers) # Convert filter object to list to print result = list(filtered_numbers) print(result)
Important Notes
filter() returns a filter object, so you often convert it to a list to see the results.
If you use None as the function, filter() removes items that are false-like (e.g., empty strings, zero, None).
Summary
filter() helps pick items from a collection based on a rule.
You give it a function that returns True or False for each item.
The result is a filtered collection with only the items that passed the rule.
Practice
1. What does the
filter() function do in Python?easy
Solution
Step 1: Understand the purpose of
Thefilter()filter()function takes a function and a list, then keeps only items where the function returns True.Step 2: Compare options with the purpose
Only Selects items from a list that meet a condition describes selecting items based on a condition, which matchesfilter()'s job.Final Answer:
Selects items from a list that meet a condition -> Option CQuick Check:
filter()selects items [OK]
Hint: Remember: filter keeps items passing the test [OK]
Common Mistakes:
- Thinking filter changes items instead of selecting
- Confusing filter with map or sort
- Assuming filter adds or combines items
2. Which of these is the correct syntax to use
filter() to keep even numbers from a list nums?easy
Solution
Step 1: Recall
The correct syntax isfilter()syntaxfilter(function, iterable), where function tests each item.Step 2: Check each option
filter(lambda x: x % 2 == 0, nums) useslambda x: x % 2 == 0as function andnumsas iterable, which is correct.Final Answer:
filter(lambda x: x % 2 == 0, nums) -> Option AQuick Check:
filter(function, iterable) correct order [OK]
Hint: filter(function, iterable) order matters [OK]
Common Mistakes:
- Swapping function and iterable arguments
- Using expression instead of function
- Missing lambda or function for filtering
3. What is the output of this code?
nums = [1, 2, 3, 4, 5] even_nums = list(filter(lambda x: x % 2 == 0, nums)) print(even_nums)
medium
Solution
Step 1: Understand the filter condition
The lambda function keeps numbers wherex % 2 == 0, meaning even numbers.Step 2: Apply filter to the list
From[1, 2, 3, 4, 5], only 2 and 4 are even, so the filtered list is[2, 4].Final Answer:
[2, 4] -> Option BQuick Check:
Filter keeps even numbers [OK]
Hint: Filter keeps items where function returns True [OK]
Common Mistakes:
- Confusing even and odd numbers
- Forgetting to convert filter to list
- Expecting original list unchanged
4. Find the error in this code snippet:
nums = [10, 15, 20] result = filter(x % 10 == 0, nums) print(list(result))
medium
Solution
Step 1: Check filter function argument
The first argument tofilter()must be a function, butx % 10 == 0is an expression, not a function.Step 2: Identify fix
We need to wrap the expression in a lambda:lambda x: x % 10 == 0to make it a function.Final Answer:
Missing lambda function for filter -> Option DQuick Check:
filter needs a function as first argument [OK]
Hint: filter needs a function, use lambda for expressions [OK]
Common Mistakes:
- Passing expression instead of function
- Assuming filter returns list directly
- Ignoring syntax errors in lambda usage
5. You have a list of words:
words = ['apple', '', 'banana', None, 'cherry', '']. Which code correctly filters out empty strings and None values using filter()?hard
Solution
Step 1: Understand filtering out empty and None
Empty strings and None are 'falsy' in Python, solambda w: wkeeps only truthy values.Step 2: Check each option
list(filter(lambda w: w, words)) keeps only truthy values, removing empty strings and None. Options B and C keep only empty or None, which is opposite. list(filter(lambda w: w != None or w != '', words)) uses wrong logic and keeps all.Final Answer:
list(filter(lambda w: w, words)) -> Option AQuick Check:
filter withlambda w: wremoves falsy values [OK]
Hint: Use
lambda x: x to remove falsy values [OK]Common Mistakes:
- Using wrong condition to keep empty or None
- Using 'or' instead of 'and' in condition
- Expecting filter to remove without function
