Python filter() Function

This function returns an iterator that yields the items that are either true, or items for which the filter function returns true.

Syntax

Python
filter(func = None, iterable)

Parameters

ParameterDescription
func Optional. If provided, the filter function will return only those items that, when pased to this function, result in func returning True. The Default is None, meaning that items in the iterator that are True will be returned.
iterable Required. An iterable object containing the items to be filtered.

Example

Python
def isEven(n):
return n % 2 == 0

def isOdd(n):
return n % 2 == 1

numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
evenNumbers = list(filter(isEven, numbers))
oddNumbers = list(filter(isOdd, numbers))

print(f'Even numbers: {evenNumbers}')
print(f'Odd numbers: {oddNumbers}')

Output

Even numbers: [2, 4, 6, 8, 10]
Odd numbers: [1, 3, 5, 7, 9]

Notes

The actual function applied during the filter can also be a lambda expression. The following code is equivalent to the code example above:

Example

Python
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
evenNumbers = list(filter(lambda n: n % 2 == 0, numbers))
oddNumbers = list(filter(lambda n: n % 2 == 1, numbers))

print(f'Even numbers: {evenNumbers}')
print(f'Odd numbers: {oddNumbers}')

Output

Even numbers: [2, 4, 6, 8, 10]
Odd numbers: [1, 3, 5, 7, 9]