Functions

Filter in Python

Filter is a built-in first class function that performs a function on a sequence, and removes all sequence elements where the function returned 'false'.


Syntax
filtered_sequence = filter(function, unfiltered_sequence)

Notes

In Python 2, the filter function returns a list by default. In Python 3, the filter function returns an iterator, which must be wrapped into a list if that's the desired result.

Like all first class functions, filters are most often used with lambdas.


Example
grades = [35, 80, 50, 60]

passed = list(filter(lambda grade: grade >= 50, grades))
#should return [80, 50, 60]

< Map   |   Class Declaration & Structure >

© 2019 SyntaxDB. All Rights Reserved.