liveBook · Manning

Lambda

As explained in The Quick Python Book, Fourth Edition

A lambda expression is an anonymous function expression that evaluates to a function value and returns the value of its expression body.

A lambda is an anonymous inline function, useful when a short function must be passed directly to another function or stored as a value. section 9.6 section 9.10

Use the compact form when the operation is simple:

  • Write lambda, followed by parameters, a colon, and one expression: lambda parameter1, parameter2: expression. section 9.6
  • Omit return; the expression's value is returned automatically. section 9.6
  • Pass the function inline when a named definition would add unnecessary separation, such as a sort key. section 5.4.1
  • Store lambdas in data structures when a small operation belongs alongside related values. section 9.6

Sort words by length

Given word_list = ['Python', 'is', 'better', 'than', 'C'], use word_list.sort(key=lambda x: len(x)). The result is ['C', 'is', 'than', 'Python', 'better']. For descending order, prefer sort(reverse=True) or reverse after a standard sort rather than using a custom sort key. section 5.4.1

t2 = {'FtoK': lambda deg_f: 273.15 + (deg_f - 32) * 5 / 9,
      'CtoK': lambda deg_c: 273.15 + deg_c}             #1
t2['FtoK'](32)
 
273.15
#1 lambda functions as dictionary values

A dictionary can keep conversion operations in one place: t2['FtoK'](32) evaluates a lambda stored under the FtoK key. section 9.6

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Defines lambda syntax, implicit returns, and practical examples, without descending into implementation details.
Examples
Demonstrates word-length sorting and temperature-conversion lambdas stored in a dictionary.
What it assumes
Assumes familiarity with function definitions, arguments, and parameters from another programming language.
What you can do after
Apply lambda expressions through Python's sort method or by storing and calling them as dictionary values.
How it connects
Connects lambda expressions to functions, first-class values, dictionary values, and the sort method.

Also explained in

Compare how 18 books explain lambda →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.