Language

Functions · Lesson 16 of 56

Filterfunction

Source: 4-Functions/4.5-filterfunction.ipynb

Start here — no coding background needed

What you will learn

Keep only items that pass a test.

In simple words

`filter` keeps elements where your function returns True — like passing students only.

Write a recipe once, use it many times — functions save repetition.

Easy example — try this first

Easy example — run this first. Change values and press Run again.

Python

Runs in your browser via Pyodide — no server. First run may take a few seconds.

Reference notes (from full bootcamp)

Optional — deeper detail for when you are ready

The filter() Function in Python

The filter() function constructs an iterator from elements of an iterable for which a function returns true. It is used to filter out items from a list (or any other iterable) based on a condition.

Reference example
Python

Runs in your browser via Pyodide — no server. First run may take a few seconds.

Reference example
Python
Output
Expected (from notebook):
True

Runs in your browser via Pyodide — no server. First run may take a few seconds.

Reference example
Python
Output
Expected (from notebook):
[2, 4, 6, 8, 10, 12]

Runs in your browser via Pyodide — no server. First run may take a few seconds.

Reference example
Python
Output
Expected (from notebook):
[6, 7, 8, 9]

Runs in your browser via Pyodide — no server. First run may take a few seconds.

Reference example
Python
Output
Expected (from notebook):
[6, 8]

Runs in your browser via Pyodide — no server. First run may take a few seconds.

Reference example
Python
Output
Expected (from notebook):
[{'name': 'Anshul', 'age': 32}, {'name': 'Jack', 'age': 33}]

Runs in your browser via Pyodide — no server. First run may take a few seconds.

Conclusion

The filter() function is a powerful tool for creating iterators that filter items out of an iterable based on a function. It is commonly used for data cleaning, filtering objects, and removing unwanted elements from lists. By mastering filter(), you can write more concise and efficient code for processing and manipulating collections in Python.

Practice test — try yourself

Write code, press Check. Wrong answer shows the correct code to copy & run.

You learned "Filterfunction". Use print() to show: Done: Filterfunction

Hint: Use one print() with the exact text.

Python