109 of 151 menu

The filter function

The filter function filters the elements of an iterable object, leaving only those that match a certain condition. The first parameter specifies the callback function by which the object will be filtered. The second parameter specifies the object itself for filtering.

Only those elements remain in the object for which the callback returns True.

The function returns a special iterable object as its result. It can be converted to a list using the list function.

Syntax

filter(function, object for filtering)

Example

Let's filter the original list to get a list consisting of only even elements:

lst = [2, 3, 6, 8, 15] res = filter(lambda x: x % 2 == 0, lst) print(list(res))

Result of code execution:

[2, 6, 8]

Example

Now let's filter out only the odd elements:

lst = [2, 3, 6, 8, 15] res = filter(lambda x: x % 2 != 0, lst) print(list(res))

Result of code execution:

[3, 15]

See also

  • method sort,
    which sorts the elements of a list
  • function sorted,
    which returns a sorted list of iterable objects
  • function map,
    which iterates over iterable objects
byenru