Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Filter Function in use | Higher-Order Functions and Lambdas
Functional Programming Concepts in Python
Section 2. Chapter 3
single

single

bookFilter Function in use

Swipe to show menu

You have already seen how higher-order functions like map allow you to apply a function to each element in a sequence. Another essential higher-order function in Python is filter.

The filter function is used to select elements from a sequence based on whether they satisfy a certain condition. It takes two arguments: a function that returns True or False for each element, and the sequence to filter. The result is an iterator containing only those elements for which the function returns True. This makes filter especially useful when you want to extract specific items from a list, tuple, or other iterable based on a criterion, such as even numbers, positive values, or strings of a certain length.

123456
def is_even(n): return n % 2 == 0 numbers = [1, 2, 3, 4, 5, 6] even_numbers = list(filter(is_even, numbers)) print(even_numbers)
copy

This code uses the filter() function to create a new list containing only the even integers from an existing collection. It works by defining a predicate function, is_even(n). The filter function iterates through the numbers list, applying this check to every element and discarding any that fail the condition. Finally, the resulting filter object is converted back into a list, producing the output.

Note
Note

When you use the filter function, it returns a filter object, which is an iterator — not a list. If you print the result of filter directly, you will see output similar to:

<filter object at 0xfffec885eb30>

To access the filtered values as a list, you must convert the filter object using list().

Task

Swipe to start coding

You are going to use the filter function to select positive numbers from a list.

  • The is_positive function should return True if the argument is greater than zero, and False otherwise.
  • The filter_positive function should use the filter function with is_positive to create a new list containing only the positive numbers from the input list.
  • The function should return this new list.
  • Do not forget to remove pass.

Solution

Switch to desktopSwitch to desktop for real-world practiceContinue from where you are using one of the options below
Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 3
single

single

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

some-alt