Functions as values

Topic 4 of 5 in Functions6 min readBeginnerFree course

Overview

In Python, a function is a value like any other — just as 42 and "hello" are. You can give it another name, store it in a list, pass it to another function, or return it from one. That idea unlocks some of Python’s most useful tools, starting with sorting things exactly the way you want.

Functions are objects

Python
def shout(text):
    return text.upper() + "!"

yell = shout          # no brackets: refer to the function, don't call it
print(yell("hi"))     # HI!
print(shout)          # <function shout at 0x...>

The brackets are what call a function. Without them, you’re talking about the function itself.

Passing a function: key=

The best-known use: sorted(), min(), max() and list.sort() take a key function. Python calls it once per item and compares the results instead of the items themselves:

Passing a function: sorted(…, key=…). With words = [“kiwi”, “Apple”, “fig”, “banana”], sorted(words, key=len) gives [“fig”, “kiwi”, “Apple”, “banana”] because len turns “kiwi” into 4, “Apple” into 5, “fig” into 3 and “banana” into 6. sorted(words, key=str.lower) gives [“Apple”, “banana”, “fig”, “kiwi”]. key is called once per item; items are ordered by the results. The original list is unchanged.

Python
words = ["kiwi", "Apple", "fig", "banana"]

sorted(words)                    # ['Apple', 'banana', 'fig', 'kiwi'] — capitals first
sorted(words, key=len)           # ['fig', 'kiwi', 'Apple', 'banana'] — by length
sorted(words, key=str.lower)     # ['Apple', 'banana', 'fig', 'kiwi'] — ignore case
max(words, key=len)              # 'banana'

Note we pass len, not len() — we hand over the function for sorted to call. When two items have equal keys, they keep their original order: Python’s sorting is stable, so sorted(["bb", "aa", "c"], key=len) gives ['c', 'bb', 'aa'].

lambda: tiny unnamed functions

For a one-off key, defining a whole function is overkill. A lambda creates a small function in place:

Python
students = [{"name": "Asha", "score": 91}, {"name": "Ben", "score": 78}]

sorted(students, key=lambda s: s["score"])                 # by score
sorted(students, key=lambda s: s["score"], reverse=True)   # highest first
max(students, key=lambda s: s["score"])                    # the top student

lambda s: s["score"] means “a function that takes s and returns s["score"]”. A lambda is limited to a single expression (no statements, no return keyword). If it gets complicated, write a normal def with a good name — it’s just as valid as a key.

Sorting by several things

Return a tuple from the key; tuples compare item by item:

Python
# by score (highest first), then by name alphabetically for ties
sorted(students, key=lambda s: (-s["score"], s["name"]))

map and filter

Two classic built-ins take a function and a collection:

Python
prices = [3.5, 12.0, 7.25]
list(map(round, prices))                     # [4, 12, 7] — apply to each
list(filter(lambda p: p > 5, prices))        # [12.0, 7.25] — keep where True

Both return lazy iterators, hence the list(...). In modern Python, comprehensions usually say the same thing more clearly — [round(p) for p in prices], [p for p in prices if p > 5] — but map is neat when you already have a named function.

Writing functions that take functions

You can write your own:

Python
def apply_to_all(func, values):
    return [func(v) for v in values]

apply_to_all(str.upper, ["a", "b"])     # ['A', 'B']
apply_to_all(abs, [-3, 4, -5])          # [3, 4, 5]

A function that takes or returns other functions is called a higher-order function. They let you separate what to do to each item from how to go through the items.

Functions in data structures

Functions can be dictionary values — a neat replacement for long if/elif chains:

Python
def add(a, b): return a + b
def sub(a, b): return a - b

operations = {"+": add, "-": sub}
print(operations["+"](10, 3))      # 13

Returning functions: closures

A function can define and return another function. The inner function remembers the variables of the outer one, even after the outer function has finished:

Python
def make_multiplier(n):
    def multiply(x):
        return x * n        # n comes from the enclosing function
    return multiply

double = make_multiplier(2)
triple = make_multiplier(3)
double(5)      # 10
triple(5)      # 15

Each returned function carries its own n — this is called a closure. It’s the “Enclosing” step of the LEGB rule from the last lesson, and it’s the basis of decorators, a feature you’ll meet in frameworks like Flask (@app.route(...)) and pytest.

The key idea: brackets call a function; no brackets pass it around. key= functions are the everyday use — sorting, min and max by any rule you like.

Exercise

Sorting and transforming students

Using the list of student dictionaries: (1) print the names sorted by score, highest first, using sorted with a key lambda; (2) print the student with the shortest name using min with key=; (3) write a normal function grade(student) returning "A" for 90+, "B" for 75+, else "C", and pass it to map to print every grade as a list; (4) write apply_to_all(func, values) that returns a new list with func applied to each value, and use it with str.upper on the names; (5) write make_multiplier(n) that returns a function, and use it to make double and triple.

Python
students = [
    {"name": "Asha", "score": 91},
    {"name": "Benedict", "score": 78},
    {"name": "Chen", "score": 85},
    {"name": "Dee", "score": 62},
]

# 1. Names sorted by score, highest first

# 2. Student with the shortest name

# 3. grade(student) + map

# 4. apply_to_all(func, values)

# 5. make_multiplier(n)

Summary

  • Functions are values: you can store them in variables, put them in lists and pass them as arguments — without calling them (no brackets).
  • sorted, min, max and list.sort accept key=, a function that turns each item into the value to compare.
  • lambda args: expression creates a small unnamed function — ideal for one-off keys.
  • map(func, items) applies a function to every item; filter(func, items) keeps items where it returns True — comprehensions are often clearer.
  • A function can create and return another function, which remembers the variables around it (a closure).