Contact
Evil Genius SocietyHomeLearnForumLeaderboardSocialsMessages
← Back to module

Lesson 7 of 10

A higher-order function is one that takes another function as an argument, or returns one. You met this idea with sorted(key=...) in the last lesson. Python has a few more worth knowing.

Functions are values

The key insight: a function name without parentheses is just a value you can pass around.

def double(x):
    return x * 2

my_func = double
print(my_func(5))

double is the function; double(5) calls it. Leaving off the parentheses hands over the function itself.

map()

map(function, sequence) applies a function to every item.

numbers = [1, 2, 3, 4]
doubled = map(lambda n: n * 2, numbers)
print(list(doubled))

map() returns a lazy object, not a list — wrap it in list() to see the results. (Module 9 explains why laziness is useful.)

filter()

filter(function, sequence) keeps only the items where the function returns True.

numbers = [1, 2, 3, 4, 5, 6]
evens = filter(lambda n: n % 2 == 0, numbers)
print(list(evens))

sorted() with key

The most useful of the three in everyday code.

words = ["banana", "kiwi", "apple"]

print(sorted(words))
print(sorted(words, key=len))
print(sorted(words, reverse=True))

key=len sorts by length instead of alphabetically. Note len is passed without parentheses — you're handing over the function, not calling it.

For dictionaries, a lambda picks out the field to sort on:

people = [
    {"name": "Ada", "age": 36},
    {"name": "Grace", "age": 45},
]

oldest_first = sorted(people, key=lambda p: p["age"], reverse=True)
print([p["name"] for p in oldest_first])

Comprehensions usually win

Most Python programmers prefer comprehensions over map and filter, because they read more directly:

numbers = [1, 2, 3, 4, 5, 6]

print(list(map(lambda n: n * 2, numbers)))
print([n * 2 for n in numbers])

print(list(filter(lambda n: n % 2 == 0, numbers)))
print([n for n in numbers if n % 2 == 0])

The comprehension versions are shorter and don't need list() around them. Use map/filter when you already have a named function to apply:

words = [" ada ", " grace "]
print([w.strip() for w in words])
print(list(map(str.strip, words)))

sorted(key=...) has no comprehension equivalent, so that one stays essential.

Try it yourself

Sort the words by length, then build a list of their lengths.

Checkpoint

  • A function name without () is a value you can pass to another function.
  • map() transforms every item; filter() keeps matching items; both return lazy objects.
  • sorted(seq, key=f) sorts by whatever f returns; add reverse=True to flip it.
  • Prefer comprehensions to map/filter, but sorted(key=...) is irreplaceable.

Questions about this lesson

Log in to ask a question.