Functions as values in Python
Functions are objects: pass them, store them, return them.
def apply_twice(fn, value):
return fn(fn(value))
def add_five(n):
return n + 5
result = apply_twice(add_five, 10)
celsius = [0, 20, 37, 100]
fahrenheit = list(map(lambda c: c * 9 / 5 + 32, celsius))
warm = list(filter(lambda c: c > 15, celsius))
operations = {"double": lambda n: n * 2, "square": lambda n: n * n}
answer = operations["square"](12)
How it works
apply_twicereceives a function and calls it twice.mapandfiltertransform lists with lambdas.- A dict of lambdas dispatches operations by name.
Keywords and builtins used here
add_fiveapply_twicedeffilterlambdalistmapreturn
The run, in numbers
- Lines
- 16
- Characters to type
- 353
- Tokens
- 117
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 74 seconds.
Step 4 of 6 in Functions, step 36 of 72 in Language basics.