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

Python closures: capture loop values at the intended time

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

A closure retains access to names from an enclosing scope, so later calls can observe the value those names hold at call time.

Download Python source kit

Operation contract

The incorrect review callbacks all refer to the same loop name after the loop finishes, yielding the final identifier three times. The corrected callbacks use a default argument to bind each current identifier while constructing the callable. The two lists of results expose the difference without relying on timing or threads.

Failure and ownership boundary

Capturing an object reference does not copy the object. A callback can still observe later mutations even when its default stores the intended reference. Use Python function arguments: avoid shared mutable defaults and Python variables: names refer to objects, assignment does not copy before assuming value capture provides an immutable snapshot.

Working program

python
late_callbacks = []
fixed_callbacks = []
for receipt_id in [41, 42, 43]:
    late_callbacks.append(lambda: receipt_id)
    fixed_callbacks.append(lambda captured=receipt_id: captured)
print([callback() for callback in late_callbacks])
print([callback() for callback in fixed_callbacks])

Output

Output
[43, 43, 43]
[41, 42, 43]

Costs and limits

Building n callbacks takes O(n) retained callables. Captured large objects can remain alive while callbacks retain their references, even after the outer operation finishes.

Common Mistakes

  • Loop closures can observe the final loop value.
  • Binding a reference is not copying its object.

Connected lessons

Python function arguments: avoid shared mutable defaults, Python decorators: preserve metadata and expose wrapper behavior, Java lambdas: function contracts and captured state.

Apply this boundary

Python scope: local assignment, nonlocal state and late binding, Python iterator interview: lazy calls, exhaustion and partial failure.

Trace the related workflow

Python interview: a comprehension has its own loop-variable scope.

python
closures
Storage details