Skip to main content

Functions as Values

intermediate14 min readLesson 59 of 169

Pass behavior around: higher-order functions, lambdas, zip, enumerate, and closures.

In Python, a function is a value โ€” you can store it, pass it, return it:

def shout(text):
    return text.upper() + "!"

def whisper(text):
    return text.lower() + "..."

actions = [shout, whisper]          # functions in a list
for act in actions:
    print(act("hello"))             # call through the variable

A function that takes or returns another function is higher-order โ€” the foundation of callbacks, decorators, and plugin systems:

def apply_twice(fn, value):
    return fn(fn(value))

apply_twice(lambda n: n * 2, 3)     # 12

lambda is a one-expression anonymous function โ€” perfect as a tiny throwaway behavior, never for complex logic.

zip and enumerate: the pair-programming duo

names = ["An", "Binh", "Chi"]
scores = [8, 9, 7]
for name, score in zip(names, scores):      # walk two sequences together
    print(name, score)

for i, name in enumerate(names, start=1):   # index + value, cleanly
    print(i, name)

Closures: functions that remember

An inner function can capture variables from the function that built it:

def make_adder(n):
    def add(x):
        return x + n        # remembers n
    return add

add5 = make_adder(5)
add5(10)                    # 15

This "factory returning a configured function" pattern powers configuration, middleware, and dependency wiring in real codebases.

Now practice

Higher-Order Function DrillsWrite functions that accept, return, and remember.3 challenges ยท ยท ~30 min