Skip to content

Module 17 · Advanced Python Concepts — topic 7 of 14

First-class functions

Functions as values: assigning functions to names, storing them in data structures, passing them as arguments, returning them from functions, and building pipelines with higher-order functions.

Beginner 10 min read·Lesson 253 of 306 in Python Programming

Learning objectives

  • Treat functions as values
  • Write and use higher-order functions
  • Build dispatch tables and processing pipelines

Definition

In Python, functions are first-class objects: they can be assigned to variables, stored in lists and dictionaries, passed to other functions and returned from functions, exactly like numbers or strings.

Introduction

sorted(names, key=str.lower) passes a function to another function. That simple idea — functions as values — powers callbacks, decorators and much of functional programming.

Why it matters

Treating behaviour as data leads to shorter, more flexible code: one function can be customised by the functions you pass in.

Detailed explanation

A def statement creates a function object and binds it to a name; another name can refer to the same function (speak = shout).

Functions have attributes such as __name__ and __doc__, and callable(obj) tells you whether something can be called.

Functions can be stored in containers: a dictionary mapping operators or commands to functions is a dispatch table that replaces long if/elif chains.

A higher-order function takes functions as arguments or returns them: sorted(key=...), map, filter, min/max(key=...).

lambda creates small anonymous functions inline, useful for short key functions.

Functions that create and return other functions (factories) are the basis of closures and decorators, covered next.

Pipelines apply a list of functions one after another, making processing steps easy to reorder and extend.

Syntax

Python
def shout(text):
return text.upper()
speak = shout # assign
actions = {"shout": shout} # store
sorted(words, key=len) # pass
def make_adder(n): # return
return lambda x: x + n
  • Functions are objects.
  • Pass and return them freely.
  • Dispatch tables replace if/elif chains.

Code examples

Functions as values

Python
def shout(text):
return text.upper() + "!"
speak = shout
print(speak("hello"), speak is shout, shout.__name__)
Output
HELLO! True shout

Storing and passing functions

Python
ops = {"+": lambda a, b: a + b, "-": lambda a, b: a - b, "*": lambda a, b: a * b}
print([ops[o](6, 3) for o in "+-*"])
print(sorted(["banana", "Kiwi", "apple"], key=str.lower))
Output
[9, 3, 18]
['apple', 'banana', 'Kiwi']

More examples

Composing and pipelines

Python
def compose(*funcs):
def run(x):
for f in reversed(funcs):
x = f(x)
return x
return run
strip_upper = compose(str.upper, str.strip)
print(strip_upper(" hello "))
def apply_all(value, steps):
for step in steps:
value = step(value)
return value
pipeline = [str.strip, str.lower, lambda s: s.replace(" ", "-")]
print(apply_all(" Learn Python Today ", pipeline))
print(list(map(len, ["a", "abc"])), list(filter(str.isdigit, ["1", "x", "22"])))
def make_multiplier(n):
return lambda x: x * n
double, triple = make_multiplier(2), make_multiplier(3)
print(double(5), triple(5), callable(double))
Output
HELLO
learn-python-today
[1, 3] ['1', '22']
10 15 True

Step-by-step explanation

  • compose returns a new function that applies the given functions from right to left, like mathematical composition.
  • The pipeline is just a list of functions applied in order; adding a step means adding an item.
  • make_multiplier returns a different function each time, each remembering its own n.

Expected output

Running “Composing and pipelines” prints exactly:

TextOutput
HELLO
learn-python-today
[1, 3] ['1', '22']
10 15 True

Practical applications

  • Callback functions in GUIs and web frameworks.
  • Command dispatchers in chatbots and command-line tools.

Best practices

  • Use dispatch tables instead of long if/elif chains.
  • Pass functions without calling them.
  • Use def for anything more than a short expression.

Common mistakes

Calling instead of passing

Avoid

sorted(words, key=len())

Prefer

sorted(words, key=len)

key needs the function itself; len() calls it immediately (and fails).

Overusing lambda

Avoid

process = lambda data: [x for x in data if x > 0 and x % 2 == 0 and x < 100]

Prefer

def even_small_positives(data):
return [x for x in data if 0 < x < 100 and x % 2 == 0]

Named functions are easier to read, test and debug.

Important notes

  • functools.partial creates a new function with some arguments pre-filled: partial(pow, exp=2).

Key takeaways

  • Functions are objects you can assign, store, pass and return.
  • Higher-order functions take or return functions.
  • Dispatch tables and pipelines use functions as data.

Try it yourself

  1. 1
    Build a calculator using a dictionary of operator functions.
  2. 2
    Write apply_n(func, n, x) that applies func to x n times.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • AdvancedWhat is printed?
Practise this topic