Skip to content
Higher-Order Functions
step 1/7

Reading — step 1 of 7

Learn

~3 min readFunctions

Here's an idea that changes how you think about code: in Python, functions are values. You can store a function in a variable, pass it as an argument to another function, and return it from a function — just like a number or a string.

A function that takes another function as input — OR returns one as output — is called a higher-order function. Sorting by a custom key, filtering, mapping, decorators, callbacks: all higher-order functions.

Functions as values

python

This is the foundation of higher-order functions.

sorted with a key function

python

key accepts a function that's called for each element to produce a sort value. The original elements are sorted by their key values.

For sorting tuples by a specific position:

python

lambda — anonymous functions

lambda creates a small one-line function on the fly:

python

Lambdas are limited — exactly ONE expression, no statements. They're useful for short callbacks where naming the function would be overkill:

python

For anything more complex than a single expression, use a regular def. Don't twist a lambda into a contortion.

map — apply a function to each element

python

map(func, iterable) returns an iterator. Wrap with list() to materialize.

In modern Python, a list comprehension is often clearer:

python

Use map mainly when the function already exists with the right signature: list(map(int, ["1", "2", "3"])).

filter — keep only items that match

python

Again, comprehensions often win for clarity: [x for x in nums if x % 2 == 0].

reduce — collapse a sequence to one value

In Python 3, reduce lives in functools:

python

Useful when there's no built-in function for what you want to combine. For sums and counts, just use sum() and len().

Returning functions — closures

A function defined inside another function captures variables from the enclosing scope:

python

This pattern — a function that returns another function — is called a closure. It's the foundation of decorators (in Python Advanced).

Common mistakes

  • Using lambda when you should use def: if it doesn't fit on one line, use a real function.
  • Confusing map(func, iter) with func(*iter): map applies func to each element; * unpacks iter into separate args.
  • Not realizing map/filter return iterators in Python 3: m = map(f, xs); list(m) works once. Reusing the same iterator gives [] the second time.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…

Higher-Order Functions — Python in Practice