liveBook · Manning

Lambda

As explained in Python Workout, Second Edition

lambda is Python syntax for creating an anonymous function from parameters and a single expression.

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

How Python Workout, Second Edition covers it

How deep it goes
Explains function objects, inline use, and readability tradeoffs, but stops short of broader lambda semantics.
Examples
Uses country dictionaries, string sorting, and a greeting callback to demonstrate anonymous functions.
What it assumes
Assumes familiarity with Python functions, sorted, dictionaries, and function arguments while connecting def to function objects.
What you can do after
Apply lambda to create one-use sorting keys and pass anonymous callbacks to functions.
How it connects
Connects lambda with sorted, key functions, function objects, def, callbacks, and operator.itemgetter.

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 Workout, Second Edition. The section links point to the parts of the book it draws on.