0
0
Pythonprogramming~10 mins

filter() function in Python - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - filter() function
Start with iterable
Apply function to each item
Function returns True?
NoSkip item
Yes
Keep item in result
Repeat for all items
Return filtered iterable
The filter() function checks each item in a list with a function. If the function says True, the item stays; if False, it is skipped.
Execution Sample
Python
numbers = [1, 2, 3, 4, 5]
def is_even(n):
    return n % 2 == 0
filtered = filter(is_even, numbers)
print(list(filtered))
This code keeps only even numbers from the list.
Execution Table
StepCurrent Item (n)Function is_even(n)ResultActionFiltered List So Far
111 % 2 == 0 -> FalseFalseSkip 1[]
222 % 2 == 0 -> TrueTrueKeep 2[2]
333 % 2 == 0 -> FalseFalseSkip 3[2]
444 % 2 == 0 -> TrueTrueKeep 4[2, 4]
555 % 2 == 0 -> FalseFalseSkip 5[2, 4]
End---All items checked[2, 4]
💡 All items processed, filter returns only items where function returned True.
Variable Tracker
VariableStartAfter 1After 2After 3After 4After 5Final
n-12345-
filtered list[][][2][2][2, 4][2, 4][2, 4]
Key Moments - 2 Insights
Why does the filter skip some items instead of keeping all?
Because the function returns False for those items (see execution_table rows 1, 3, 5), filter only keeps items where the function returns True.
Is the filter result a list immediately?
No, filter returns an iterator. We convert it to a list with list(filtered) to see the results, as shown in the execution_sample code.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the filtered list after step 4?
A[2]
B[1, 2, 3, 4]
C[2, 4]
D[1, 3, 5]
💡 Hint
Check the 'Filtered List So Far' column at step 4 in the execution_table.
At which step does the function return True for the first time?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Look at the 'Function is_even(n)' and 'Result' columns in the execution_table.
If the function always returned True, what would the filtered list be after all steps?
A[]
B[1, 2, 3, 4, 5]
C[2, 4]
D[1, 3, 5]
💡 Hint
If function returns True for every item, filter keeps all items (see concept_flow).
Concept Snapshot
filter(function, iterable)
- Applies function to each item
- Keeps items where function returns True
- Returns an iterator
- Convert to list to see results
- Useful to select items by condition
Full Transcript
The filter() function takes a list and a function. It checks each item with the function. If the function returns True, the item is kept; if False, it is skipped. The result is an iterator that can be converted to a list. For example, filtering even numbers keeps only numbers divisible by 2. Step by step, each item is tested and either added or skipped. This helps select items easily without writing loops.