Ad space (banner)
🐍Python Lessons
Lesson 30 / 69

Higher-Order Functions (passing a function as an argument)

This lesson covers the idea of higher-order functions in Python, so you can write flexible code by passing a function as an argument. It's written for anyone searching "Python higher-order functions" or "Python sorted key usage".

Being able to pass one function as an argument to another is called a higher-order function. Think of it like "specifying only how the work should be done, and letting someone else actually do it." Passing a comparison key to sorted() is a classic example. The map() you learned earlier is actually a kind of higher-order function too, since it accepts a function as an argument.

The sample code defines a function, by_descending, and passes it as the key argument, like sorted(nums, key=by_descending). Sorting is based on the value returned by the function passed to key — it's also common to write this concisely as a lambda, like key=lambda n: -n.

A common beginner mistake is misunderstanding the relationship between sorted()'s key argument and the actual sort order. The function passed to key returns "the value used for sorting" — it isn't a function that directly determines order. There's also a reverse=True option if you just want descending order.

Once you can write your own higher-order functions, shared logic becomes much easier to package up and reuse. It's one of the key ideas behind modern Python code, and it's put to work in all kinds of data-processing tasks.

Python
OUTPUT

💡 The Python engine may take a few seconds to load the first time you run code.

Ad space (banner)
Ad space (in-article)