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.

  1. Concepts
  2. Questions
  3. Sort and link
  4. Scenarios
  5. 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: i prints [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)).

    key receives each element and returns the value to compare on; the minus sign reverses the order. You can also write reverse=True with key=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=...), map and filter are 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 with lambda: show(n). All display 2. Which fix is right?

    • Replace range(3) by range(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=n is evaluated when each lambda is created and freezes the current value. Calling show(n) right away would run it instead of waiting for the click.