Skip to content

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.

Beginner 8 min read·Lesson 141 of 306 in Python Programming

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

Python
square = lambda x: x * x
sorted(students, key=lambda s: s["marks"], reverse=True)
max(words, key=lambda w: len(w))
list(filter(lambda n: n % 2 == 0, numbers))
  • One expression, returned automatically.
  • Best used inline as a key or callback.
  • Use def for anything longer.

Code examples

Lambdas as values

Python
add = lambda a, b: a + b
parity = lambda n: "even" if n % 2 == 0 else "odd"
print(add(3, 4), parity(7), (lambda: "no args")())
Output
7 odd no args

map and filter

Python
prices = [100, 250, 80]
with_tax = list(map(lambda p: round(p * 1.18, 2), prices))
cheap = list(filter(lambda p: p < 150, prices))
print(with_tax, cheap)
print([round(p * 1.18, 2) for p in prices], [p for p in prices if p < 150])
Output
[118.0, 295.0, 94.4] [100, 80]
[118.0, 295.0, 94.4] [100, 80]

More examples

Sorting with key functions

Python
students = [
{"name": "Ravi", "marks": 74, "age": 20},
{"name": "Asha", "marks": 91, "age": 19},
{"name": "Meera", "marks": 91, "age": 18},
]
by_marks = sorted(students, key=lambda s: (-s["marks"], s["name"]))
print([s["name"] for s in by_marks])
youngest = min(students, key=lambda s: s["age"])
print(youngest["name"])
words = ["kiwi", "Banana", "apple"]
print(sorted(words), sorted(words, key=str.lower), sorted(words, key=len))
Output
['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:

TextOutput
['Asha', 'Meera', 'Ravi']
Meera
['Banana', 'apple', 'kiwi'] ['apple', 'Banana', 'kiwi'] ['kiwi', 'apple', 'Banana']

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

key=lambda r: r[2] if r[3] else (r[1] if r[0] > 5 else r[4])

Prefer

def sort_key(r):
...
sorted(rows, key=sort_key)

If it doesn't fit comfortably on one line, use a named function.

Calling the key yourself

Avoid

sorted(items, key=len(items))

Prefer

sorted(items, key=len)

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

  1. 1
    Sort a list of (name, city, age) tuples by city and then by age descending.
  2. 2
    Rewrite 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?
Practise this topic