Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Python lambda functions: one expression and the same closure rules

Last updated: 30 Sept 20264 min read
tutorial
BeginnerBy AITrove Editorial

A lambda creates a function from one expression and captures enclosing names under the same binding rules as other nested functions.

Download Python source kit

Operation contract

The dispatch sort key selects priority and then receipt ID so tied priorities have an explicit presentation order. Sorting produces a separate outer list. The callback list binds the current receipt ID as a default argument; otherwise later calls would read the loop name’s final binding. Lambda changes the syntax, not the ownership model.

Failure and ownership boundary

A key function should not mutate the collection being sorted. A captured mutable object remains shared even when its reference was bound through a default. Multi-step validation, logging and failure handling are easier to review in a named function than in a crowded expression. Python scope: local assignment, nonlocal state and late binding and Python sorting: stable keys, independent output and explicit tie rules supply the underlying behavior.

Working program

python
receipts = [(2, "R-0042"), (1, "R-0041"), (2, "R-0040")]
ordered = sorted(receipts, key=lambda receipt: (receipt[0], receipt[1]))
print(ordered)
callbacks = [lambda receipt_id=receipt_id: receipt_id for receipt_id in ("R-0041", "R-0042")]
print([callback() for callback in callbacks])
print("input unchanged:", receipts[0] == (2, "R-0042"))

Output

Output
[(1, 'R-0041'), (2, 'R-0040'), (2, 'R-0042')]
['R-0041', 'R-0042']
input unchanged: True

Costs and limits

Sorting n entries has O(n log n) worst-case comparison work and O(n) auxiliary storage in this use. Key construction adds its own per-entry work. Creating n callbacks retains O(n) functions/default references.

Common Mistakes

  • Lambda does not freeze every captured value.
  • Use a named function when an expression hides several domain decisions.

Connected lessons

Python scope: local assignment, nonlocal state and late binding, Python function arguments: avoid shared mutable defaults, Python sorting: stable keys, independent output and explicit tie rules.

python
lambda-functions
Storage details