ReviseAlgo Logo

Functions

Lambda Functions

Anonymous inline functions for concise functional expressions

Interview: Common in interviews — sorting with custom keys, map/filter, and callback patterns

Last Updated: June 12, 2026 8 min read

Lambda functions are small, anonymous (unnamed) functions defined with the lambda keyword. They can have any number of arguments but only a single expression. They're ideal for short, throwaway functions used as arguments to higher-order functions like sorted(), map(), and filter().

Lambda Syntax

  • Basic form: lambda arguments: expression — the expression's value is returned automatically
  • No return keyword: The expression result is implicitly returned — no statements allowed
  • Single expression: Only one expression — no if/else blocks, loops, or assignments (but ternary is OK)
  • Anonymous: Has no __name__ (shows as "<lambda>") — assign to variable if you need a name

Common Use Cases

  • Sorting with custom key: sorted(items, key=lambda x: x[1]) — sort tuples by second element
  • map/filter: list(map(lambda x: x*2, nums)) — though comprehensions are often preferred
  • Event callbacks: button.onclick = lambda: handle_click()
  • Default argument capture: lambda x=i: x — captures current loop value
  • min/max with key: max(dicts, key=lambda d: d['score'])

Lambda vs def: Style Guide

PEP 8 recommends using def instead of assigning lambdas to variables: def square(x): return x**2 is preferred over square = lambda x: x**2. Use lambdas for inline, throwaway functions only.

Lambda Limitations

  • No statements: Can't use if/elif/else blocks, for/while loops, try/except, or assignments
  • No annotations: Can't add type hints to lambda parameters
  • No docstrings: Can't document what the lambda does
  • Hard to debug: Stack traces show "<lambda>" instead of a meaningful function name

Ternary in Lambda

While you can't use if/else blocks, you CAN use the ternary expression: lambda x: "even" if x % 2 == 0 else "odd". This is a common pattern for conditional transformations in map/filter.

Use Cases

Custom sort keys for sorted(), min(), max() with complex data structures

Inline transformations with map() and filtering with filter()

Callback functions for event handlers and GUI programming

Dispatch tables mapping operation names to anonymous functions

Quick one-off functions in functional pipelines (reduce, sorted, groupby)

Common Mistakes

Assigning lambda to a variable — PEP 8 says use def instead for named functions

Late binding in loops — lambdas capture variable names, not values; use default args to fix

Trying to use statements (if blocks, loops, try/except) in lambda — only expressions allowed

Using lambda when a comprehension would be more readable

Forgetting that lambdas have no __name__ — makes debugging stack traces harder