liveBook · Manning

Lambda

As explained in Python How-To

The lambda keyword introduces a Python expression that defines an anonymous function.

Need a short function just once, such as extracting a sorting key? A lambda defines an anonymous function where it is needed, without a separate `def` and function name. section 7.1 section 7.1.2

Sort tasks by urgency

```python tasks = [ {'title': 'Laundry', 'urgency': 3}, {'title': 'Homework', 'urgency': 5}, {'title': 'Museum', 'urgency': 2}, ] tasks.sort(key=lambda task: task['urgency'], reverse=True) print([task['title'] for task in tasks]) # ['Homework', 'Laundry', 'Museum'] ``` The sorting method passes each task to the key function. The lambda extracts its urgency; `reverse=True` puts the highest value first. The key function takes one argument because it receives one item at a time. section 3.2.3 section 7.1.2

The form is `lambda arguments: expression`. Arguments can number zero or more, but the colon and a single expression are required. That expression supplies the function’s value: write `lambda x: x * 2`, not `lambda x: return x * 2`. A lambda is still a function and can be called with arguments like a function defined with `def`. section 7.1.1

Keep the job small and choose the clearest available function:

  • Use an inline lambda for a one-time extraction or test, such as `filter(lambda task: task.urgency > 3, tasks)`. section 7.1.2 section 5.3.5
  • Pass an existing function directly when it already does the job: `sorted(integers, key=abs)` is simpler than `key=lambda x: abs(x)`. section 7.1.3
  • Prefer a named function if you need a reusable name or clearer debugging. Assigning a lambda to a variable loses the main benefit of using it inline; a traceback identifies that function as `<lambda>` rather than by a descriptive name. section 7.1.3

How Python How-To covers it

How deep it goes
Explains syntax, expression-only bodies, calls, one-time use, and debugging trade-offs without descending into implementation internals.
Examples
Uses urgency-based task sorting, task filtering, absolute-value sorting, score selection, and contrasting KeyError tracebacks.
What it assumes
Assumes familiarity with ordinary functions and container items while teaching lambda syntax from its components.
What you can do after
Apply it via Python sorting and filtering APIs while choosing existing or named functions when they read or debug better.
How it connects
Connects anonymous functions with named functions, sorting keys, filter, higher-order functions, and built-in function alternatives.

Also explained in

Compare how 18 books explain lambda →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.