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

single

Filter Function in use

Veeg om het menu te tonen

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)

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().

Taak

Veeg om te beginnen met coderen

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.

Oplossing

Switch to desktopSchakel over naar desktop voor praktijkervaringGa verder vanaf waar je bent met een van de onderstaande opties
Was alles duidelijk?

Hoe kunnen we het verbeteren?

Bedankt voor je feedback!

Sectie 2. Hoofdstuk 3
single

single

Vraag AI

expand

Vraag AI

ChatGPT

Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.

some-alt