Lambdas in practice

Lambdas in practice

Use small functions with more confidence.

Give another function your rule.

A function can be passed as a value. Here, apply_twice takes a rule and a starting value, then calls that rule twice.

apply_twice(lambda x: x + 3, 5)
Start5input
First call—waiting
Second call—waiting

The lambda is passed in as a function. Its body hasn’t run yet.

See how apply_twice works
def apply_twice(func, value):
    return func(func(value))

The inner func(value) runs first. Its result becomes the input to the outer call. A function that accepts or returns a function is called a higher-order function.

lambda x: x + 3 creates the function to pass.
(lambda x: x + 3)(5) calls it immediately and produces 8.

The caller decides how to use the result.

Each of these functions calls a lambda for each item. What it does with the returned value is different.

words = ["pear", "fig", "banana"]
list(map(lambda word: len(word), words))
Input wordLambda returnsUsed as
"pear"4a new value
"fig"3a new value
"banana"6a new value
Result[4, 3, 6]

map uses the returned lengths as new items. len(word) counts the letters in a word.

When do these lambdas run?

map and filter return iterators: values are produced as you request them. In these examples, list(...) requests all the results, so the lambdas run then.

sorted calculates its keys and returns a new list during the call. The keys decide the order; the original items go into the result.

Review the basics: Meet map() or Introduction to filters.

More inputs. An optional default.

Separate parameters with commas. A default supplies a value when you leave that argument out.

add = lambda x, y=10: x + y
add(2)
x = 2from the call
y = 10from the default
2 + 1012

Passing 0 still supplies an argument. The default is used only when you omit y. Leaving out the required x causes a TypeError.

Can I use keyword arguments?

Yes. add(x=2, y=3) returns 5. Lambdas use the same argument rules as functions defined with def.

One expression can make a choice.

A conditional expression has two possible values. Python checks the condition and evaluates only the chosen branch.

lambda x: "Even" if x % 2 == 0 else "Odd"
4 % 2 == 0True
If true"Even"returned
Else"Odd"not evaluated

4 divides evenly by 2, so the call returns "Even".

% gives the remainder after division. A remainder of 0 means the number is even. The body is one expression: value_if_true if condition else value_if_false.

What can a lambda return?

Any value, including a number, string, Boolean, or list. For example, lambda x: [x, x * 2] returns [3, 6] when called with 3.

Returning and printing are different. lambda x: print(x) displays the input but returns None, because that is what print returns.

When a value is read matters.

The body runs when the function is called. A default is evaluated earlier, when the function is created.

Outside the functionsn = 10

Read at call time

read = lambda: n

The body will look up n when called.

read()—

Save a default at creation

remember = lambda saved=n: saved

The default for saved is now 10.

remember()—

Step 1 of 3. With n = 10, create both functions. Neither body has run.

lambda: has no parameters. remember() leaves out its optional argument, so it uses the saved default. This timing also applies to def.

Is a default always a snapshot?

No. A default stores an object reference. In this example, rebinding n to a new number leaves the old default in place. If the default were a list, changing that same list would still be visible through the default.

Keep the rule readable.

Use a lambda for a short function passed directly to another function. Prefer def for named functions you reuse or logic with several steps. The named lambdas above make the examples easier to trace.