Introduction to filters

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

123456

Your original list

Ask a question

Change the number to try a rule.

Keep the matches

456

3 of 6 kept

4, 5, and 6 pass the rule. Everything else is left out.

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)
A yes/no functionA list, for example

Let’s write the “greater than 3” example.

  1. Make the rule

    number is one item. return sends back the answer: True or False.

    def is_big(number):
        return number > 3
  2. Give it items

    This list supplies the numbers to check, one at a time.

    numbers = [1, 2, 3, 4, 5, 6]
  3. 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)
Output[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.

Try it yourself
Next lesson: Working with filters