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

















