single
Filter 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.
123456def is_even(n): return n % 2 == 0 numbers = [1, 2, 3, 4, 5, 6] even_numbers = list(filter(is_even, numbers)) print(even_numbers)
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.
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().
Swipe to start coding
You are going to use the filter function to select positive numbers from a list.
- The
is_positivefunction should returnTrueif the argument is greater than zero, andFalseotherwise. - The
filter_positivefunction should use thefilterfunction withis_positiveto 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
Thanks for your feedback!
single
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat