Python ยท Chapter 22 of 45

Python Lambda

A `lambda` is a small anonymous function limited to a single expression. Handy for short throwaway functions.

Syntax: `lambda parameters: expression`.

When to use

Use lambda for tiny functions passed as arguments to `sorted`, `map`, `filter`, etc. Define with `def` for anything longer.

Limitations

No statements (like `if/else` blocks or assignments) โ€” only a single expression that becomes the return value.

Example 1 (python)
square = lambda x: x * x
print(square(5))
Output
25

One-liner function assigned to a variable.

Example 2 (python)
pairs = [(1,"b"),(2,"a"),(3,"c")]
sorted_pairs = sorted(pairs, key=lambda p: p[1])
print(sorted_pairs)
Output
[(2, 'a'), (1, 'b'), (3, 'c')]

Sort by second element using a lambda key.

Key points

  • Anonymous single-expression function.
  • Syntax: `lambda args: expression`.
  • Great as a `key=` for sort/map/filter.
  • Prefer `def` for anything multi-line.
๐Ÿ’ก Note: Assigning a lambda to a name (`f = lambda x: ...`) is discouraged by PEP 8 โ€” use `def f(x):` instead.

๐Ÿ“ Quick Quiz

1. A lambda can contain:

2. `(lambda x: x + 1)(4)` returns:

3. A common use of lambda is: