The Filter Function
Part of the Logic & Flow section of Coddy's Python journey — lesson 73 of 78.
The filter() function takes two main things:
- A function (which contains instructions for checking each item)
- A sequence of items (like a list, or any collection of elements)
It looks at each item in your sequence, one by one, and only keeps the ones that pass the function's test (when the function returns True).
For example:
def is_even(n):
return n % 2 == 0
numbers = [1, 2, 3, 4, 5, 6] # This is just a list of numbers
even_numbers = filter(is_even, numbers)
print(list(even_numbers))
# Output: [2, 4, 6]What happened here:
- We have a list of numbers: [1, 2, 3, 4, 5, 6]
- The filter() function takes each number, one at a time
- It puts each number through our is_even function
- If the function returns True, it keeps that number
- If the function returns False, it drops that number
You can think of it like a strainer:
- Number 1 goes in →
is_evenreturns False → number dropped - Number 2 goes in →
is_evenreturns True → number kept
- Number 3 goes in →
is_evenreturns False → number dropped And so on...
You can also use a quick, one-line function (called lambda) instead of defining a separate function:
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(lambda n: n % 2 == 0, numbers)
print(list(even_numbers))
# Output: [2, 4, 6]The filter() function works with any collection of items - not just numbers. Here's an example with strings:
words = ["apple", "banana", "cherry", "date"]
long_words = filter(lambda word: len(word) > 5, words)
print(list(long_words))
# Output: ["banana", "cherry"]Challenge
EasyCreate a function named get_long_strings that takes a list of strings strings as an argument. The function should use the filter() function along with a lambda function to select strings that have a length greater than 5. The function should return a list containing the selected strings.
Cheat sheet
The filter() function takes two arguments:
- A function that returns True/False for each item
- A sequence of items to filter
It keeps only items where the function returns True:
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))
# Output: [2, 4, 6]You can use lambda functions for simple filtering:
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(lambda n: n % 2 == 0, numbers)
print(list(even_numbers))
# Output: [2, 4, 6]Filter works with any data type:
words = ["apple", "banana", "cherry", "date"]
long_words = filter(lambda word: len(word) > 5, words)
print(list(long_words))
# Output: ["banana", "cherry"]Try it yourself
def get_long_strings(strings):
# Use filter() with a lambda function to select strings with length greater than 5
long_strings =
# Return the list of selected strings
return list(long_strings)This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Variables Exploration
ConstantsMultiple Variable AssignmentsSwapping VariablesPlaceholder VariablesRound NumbersList Casting4Contact Book Application
Display MenuAdd Contact7Sets Part 2
Mathematical Operations Part 1Mathematical Operations Part 2Recap - Treasure HuntSubsets and SupersetsIterating Over SetsRecap - Tournament Tracker2Dictionaries Part 1
What is a Dictionary?Creating a DictionaryAccessing ValuesModifying DictionariesRecap - Recipe Manager5Advanced Decision Making
Ternary OperatorMembership ChecksIdentity ChecksIndentation ErrorsRecap - Vacation Filter8Student Records Manager
Project OverviewAdd Student11Advanced Functions
Returning Multiple ValuesLambda Functions Part 1Lambda Functions Part 2Recap Challenge - Lambda SortRecursive Functions Part 1Recursive Functions Part 2Recap - Sum Nested List14Higher-Order Functions
The Map FunctionThe Filter FunctionRecap - Email ValidatorRecap - Number Processor3Dictionaries Part 2
Dictionary MethodsNested DictionariesChecking for KeysLooping Through DictionariesRecap - Frequency Counter9Advanced Data Aggregation
Using SumFinding Minimum and MaximumSorting Data EfficientlyRecap - Dictionary Sorter