{:check ["true"], :rank ["filter" "list_comprehension"]}
filter is a higher-order function that keeps certain elements in an input sequence of elements.
filter(<predicate>, <iterable>)
Predicate functions:
Any function that returns a boolean is a predicate function.
def is_even(x): return x % 2 == 0
True and False in Python
Python has two boolean values
TrueandFalse, but data values in general are interpreted as boolean as well.
data values boolean interpretation NoneFalse "Hello"True ""False 3.1415True 0False {"age": 40}True {}False [1,2,3]True []False One can use the
bool(...)function to check:bool(value)
Filter makes use of predicates to keep certain elements:
# tests if a number is divisible by 3
def is_divisible_by_3(n):
return n % 3 == 0
filter(is_divisible_by_3, [1,2,3,4,5,6,7,8,9])
This can be done as a lambda function:
filter(lambda i: i % 3 == 0, [1,2,3,4,5,6,7,8,9])
Filter is lazily evaluated just like map.
Consider the following iteration pattern:
xs = [1,2,3,4,5,6,7]
result = []
for x in xs:
if x % 3 == 0:
result.append(x ** 2)
This is a combination of map and filter:
xs = [1,2,3,4,5,6,7]
result = map(lambda x: x ** 2, filter(lambda x: x%3 == 0, xs))
List comprehension is more readable syntax for filter/map pattern.
The general syntax is:
[ <expression> for <var> in <iterable> if <condition> ]
Applying list comprehension
xs = [1,2,3,4,5,6,7]
result = [x ** 2 for x in xs if x % 3 == 0]
Consider the following problem:
What are all the integer solutions to
$$ 3x - y^2 = 0 $$ for $x,y\in[0, 100]$
A simple nested loop solution
solutions = []
for x in range(100):
for y in range(100):
if 3*x - y*y == 0:
solutions.append((x, y))
A list comprehension solution
solutions = [(x, y) for x in range(100) for y in range(100) if 3*x-y*y == 0]