Reading — step 1 of 7
Learn
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
This is the foundation of higher-order functions.
sorted with a key function
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:
lambda — anonymous functions
lambda creates a small one-line function on the fly:
Lambdas are limited — exactly ONE expression, no statements. They're useful for short callbacks where naming the function would be overkill:
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
map(func, iterable) returns an iterator. Wrap with list() to materialize.
In modern Python, a list comprehension is often clearer:
Use map mainly when the function already exists with the right signature: list(map(int, ["1", "2", "3"])).
filter — keep only items that match
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:
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:
This pattern — a function that returns another function — is called a closure. It's the foundation of decorators (in Python Advanced).
Common mistakes
- Using
lambdawhen you should usedef: if it doesn't fit on one line, use a real function. - Confusing
map(func, iter)withfunc(*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…