Higher-Order Functions
Functions as arguments and return values
Interview Relevant: Functional programming
Higher-Order Functions
Functions that take or return functions.
Code Examples
Higher-order function patterns.
python
1# Function as argument
2def apply_twice(func, value):
3 return func(func(value))
4
5apply_twice(lambda x: x * 2, 3) # 12
6
7# Function as return value
8def make_adder(n):
9 return lambda x: x + n
10
11add_5 = make_adder(5)
12add_5(10) # 15
13
14# Built-in higher-order functions
15nums = [1, 2, 3, 4, 5]
16
17# map
18list(map(str, nums)) # ['1', '2', '3', '4', '5']
19
20# filter
21list(filter(lambda x: x > 2, nums)) # [3, 4, 5]
22
23# reduce
24from functools import reduce
25reduce(lambda a, b: a + b, nums) # 15
26
27# sorted with key
28sorted(["banana", "apple"], key=len)