Lambdas and closures
The function as a value: anonymous function, function passed as an argument, function returning a function, closure, captured variables and the late-binding trap in a loop.
- 18 cards
- 5 topics
- Free
The outline, topic by topic
Each topic is weighted the way the exam weighs it.
- Concepts
- Questions
- Sort and link
- Scenarios
- Understand
A few cards from the deck
Anonymous function (lambda): what is it?
Show the answer
A function defined by a single expression, without giving it a name, right where it is needed:
lambda x: x * 2.In Python, a lambda's body is a single expression whose value is returned: no statement, no
return. As soon as the logic grows, a named function is more readable.What does this program print?
```python
fs = [lambda: i for i in range(3)]
print([f() for f in fs])`[2, 2, 2][0, 1, 2][3, 3, 3][0, 0, 0]
Show the answer
[2, 2, 2]The three lambdas share the same variable
i, read at call time: the loop left it at 2. To freeze each value:lambda i=i: iprints[0, 1, 2].To sort words from longest to shortest, write sorted(words, key=lambda m: …).
Show the answer
To sort words from longest to shortest, write sorted(words, key=lambda m: -len(m)).
keyreceives each element and returns the value to compare on; the minus sign reverses the order. You can also writereverse=Truewithkey=len.Higher-order function: what is it?
Show the answer
A function that takes another function as an argument, or returns one.
sorted(list, key=...),mapandfilterare examples: the function passed describes what varies, the receiving function handles the loop.Three buttons are created in a
for n in range(3)loop, each withlambda: show(n). All display 2. Which fix is right?- Replace
range(3)byrange(1, 4) - Bind the value at creation:
lambda n=n: show(n) - Call
show(n)at creation instead of putting it in the lambda - Replace the lambda by a list comprehension
Show the answer
Bind the value at creation:
lambda n=n: show(n)The default value
n=nis evaluated when each lambda is created and freezes the current value. Callingshow(n)right away would run it instead of waiting for the click.- Replace