Python filter() built-in function

From the Python 3 documentation

Construct an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

Introduction

The filter() function in Python is a built-in function that allows you to process an iterable and extract those items that satisfy a certain condition. It returns an iterator with the elements that meet the criteria.

Syntax

filter(function, iterable)
  • function: The function to execute for each item in the iterable. It should return True or False for each item.
  • iterable: The iterable to filter, such as a list, tuple, or string.

Description

The filter() function constructs an iterator from those elements of the iterable for which the function returns True. If the function is None, it removes all elements of the iterable that are false.

Example

>>> def is_even(num):
...     return num % 2 == 0
...
>>> numbers = [1, 2, 3, 4, 5, 6]
>>> even_numbers = list(filter(is_even, numbers))
>>> print(even_numbers)
>>> [2, 4, 6]

In this example, the is_even function is defined to determine whether a number is even or not. The filter method takes two arguments: the first argument is the function to apply to each element of the list, and the second argument is the list to be filtered. The filter method returns an iterator, which is then converted to a list and stored in the even_numbers variable. The final output is the list of even numbers from the original list.

Subscribe to pythoncheatsheet.org

Join 16,702+ Python developers in a two times a month and bullshit free publication , full of interesting, relevant links.