Python 101Free
FUNCTIONS

Higher Order Functions

Treating functions as values you can pass around.

SECTION 01

Functions as values

A function in Python is just an object. You can assign it to a variable, store it in a list or dict, pass it to another function, or return it from one. There is nothing special about its name or its position in the source.

This is what people mean when they say functions are "first-class". The language treats them like any other value, and any pattern that works for ordinary values works for functions too.

Once you internalize this, a lot of patterns become obvious. Callbacks, event handlers, sorting keys, decorators, plugin systems: they all rely on passing functions around. The core feature is just "functions are values".

python
def double(x):
    return x * 2

fns = [double, abs, str]
fns[0](5)        # 10

def apply(fn, x):
    return fn(x)
apply(double, 7) # 14
SECTION 02

lambda, map, filter

lambda defines a function inline. lambda x: x * x is a tiny anonymous function that squares its argument. The body must be a single expression, which keeps lambdas honest about staying small.

map(fn, iterable) applies fn to every element. filter(pred, iterable) keeps only the elements for which pred returns truthy. Both return iterators in Python 3, so wrap them in list(...) if you need a concrete list.

In practice, comprehensions usually read better than map and filter. [x * x for x in nums] is more direct than list(map(lambda x: x * x, nums)). Reach for map when you have a named function ready to apply, and a comprehension whenever the transformation is one-off.

python
nums = [1, 2, 3, 4]
list(map(lambda x: x * x, nums))     # [1, 4, 9, 16]
list(filter(lambda x: x % 2, nums))  # [1, 3]

[x * x for x in nums]                # usually clearer
← PREVIOUS
Scope and Closures