Module 9 · Functions — topic 16 of 19
Lambda functions
Small anonymous functions written with lambda, their single-expression limit, and their main use as key functions for sorted, min, max, map and filter.
Learning objectives
- Write lambda expressions with zero, one or several parameters
- Use lambdas as key functions for sorting and selecting
- Decide when a def is clearer than a lambda
Definition
A lambda expression creates an anonymous function: lambda parameters: expression. Calling it evaluates and returns the expression. It can contain only a single expression, not statements.
Introduction
Sorting students by marks needs a tiny function: given a student, return their marks. Writing a full def for that is overkill; lambda s: s["marks"] says it in one line, right where it is used.
Why it matters
Lambdas are everywhere in idiomatic Python: sorted(..., key=lambda ...), max(..., key=...), and callbacks. Recognising when not to use them matters just as much.
Detailed explanation
Syntax: lambda x, y: x + y. The body is an expression whose value is returned automatically; there is no return keyword.
Lambdas can't contain statements such as if-blocks, loops or assignments — but they can use a conditional expression: lambda n: 'even' if n % 2 == 0 else 'odd'.
Their most common job is the key= argument: sorted(items, key=lambda item: item[1]) sorts by the second element.
map(func, iterable) applies a function to every item and filter(func, iterable) keeps items where it returns true; comprehensions are often clearer for both.
Assigning a lambda to a name (square = lambda x: x * x) works, but PEP 8 recommends def instead, because def gives the function a proper name in tracebacks.
Syntax
- One expression, returned automatically.
- Best used inline as a key or callback.
- Use def for anything longer.
Code examples
Lambdas as values
7 odd no args
map and filter
[118.0, 295.0, 94.4] [100, 80] [118.0, 295.0, 94.4] [100, 80]
More examples
Sorting with key functions
['Asha', 'Meera', 'Ravi'] Meera ['Banana', 'apple', 'kiwi'] ['apple', 'Banana', 'kiwi'] ['kiwi', 'apple', 'Banana']
Step-by-step explanation
- The key returns a tuple: negated marks (so higher marks come first) and then the name for ties.
- min with a key returns the whole dictionary with the smallest age.
- key=str.lower passes an existing function instead of a lambda; key=len sorts by length, keeping the original order for ties (sorting is stable).
Expected output
Running “Sorting with key functions” prints exactly:
Practical applications
- Sorting records by a field for reports.
- Button callbacks in GUI toolkits: command=lambda: save(document).
Best practices
- Use lambdas inline, for short key functions and callbacks.
- Prefer comprehensions over map/filter with lambdas.
- Use def when the function deserves a name.
Common mistakes
Long, unreadable lambdas
Avoid
Prefer
If it doesn't fit comfortably on one line, use a named function.
Calling the key yourself
Avoid
Prefer
key needs a function, not the result of calling one.
Important notes
- operator.itemgetter("marks") and operator.attrgetter("age") are fast, readable alternatives to simple lambdas.
Key takeaways
- lambda params: expression creates a small anonymous function.
- It can hold only one expression.
- Its main use is as a key or callback.
Try it yourself
- 1Sort a list of (name, city, age) tuples by city and then by age descending.
- 2Rewrite list(map(lambda x: x ** 2, filter(lambda x: x > 0, nums))) as a comprehension.
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.
- ModerateWhat is printed?