Introduction to filters
Keep the items that match a rule.
One list. One question.
Imagine you only want numbers greater than 3. A filter checks each number and keeps the matches.
Start with items
Your original list
Ask a question
Change the number to try a rule.
Keep the matches
3 of 6 kept
Same values. Same order. Only the matches stay.
The original list stays unchanged.
Use it in Python
filter() takes two things: a rule and items to check.
filter(rule, items)Let’s write the “greater than 3” example.
-
Make the rule
numberis one item.returnsends back the answer:TrueorFalse.def is_big(number): return number > 3 -
Give it items
This list supplies the numbers to check, one at a time.
numbers = [1, 2, 3, 4, 5, 6] -
Filter and collect
filter()selects the matches.list()collects them into a list you can see and use.result = list(filter(is_big, numbers)) print(result)
[4, 5, 6]The rule returns True or False.
The filter keeps the original numbers.
Pass is_big without (). The filter calls the function for each item.
Why do we need list()?
filter() returns an iterator: results you can read one at a time. It checks items as you ask for results. list() asks for all the remaining matches and collects them. Printing the filter object alone won’t show a list of matches.
That’s the core idea.
Items go in. A rule decides. Matches come out.
Which numbers stay?
1 of 3Select every number greater than 3, then check your selection.
You’ve got the idea.
A filter keeps the original items that match a rule,
in the order they arrived.
list(filter(rule, items))
Review the lesson