Use lambda when a sorting or callback operation needs a small function only once. It returns a function object without assigning that object a permanent variable name. section 4.11 section 4.13
A lambda expression has a deliberately narrow shape:
- It accepts parameters and evaluates one expression, such as lambda d: d['name']. section 4.11
- It can be supplied anywhere a regular function can be supplied, including as sorted's key function or as a callback. section 4.13
- Prefer a named def function when the logic deserves explanation or reuse; lambda can make code less readable. section 4.11
Sort dictionaries by a key
Instead of defining a one-use helper such as by_country_name, pass the transformation directly: sorted(COUNTRIES, key=lambda d: d['name']). For multi-key dictionary sorting, operator.itemgetter('size', 'name') is an alternative. section 4.11
def run_func_with_world(f):
return f('world')
print(run_func_with_world(lambda name: f'Hello, {name}'))
This executable example passes an anonymous function directly to another function, showing that lambda produces an ordinary callable object. section 4.13

















