Functions are values; lambda
🌍 In real life. At a print shop, you can hand over a page and an instruction card: "make it bigger" or "make it black-and-white". The shop doesn't care which card you bring; it just follows whatever card it's given. The instruction itself is something you can pass around.
In Python, a function is a value too: you can hand it to another function, which then follows it.
The idea in one sentence: a function's name without brackets is the function itself, a value you can store or pass on, and lambda writes a small function in one line.
Its words:
- function as a value:
shout(no brackets) is the function;shout("hi")is its result - higher-order function: a function that takes or returns a function, like
speak(style, text) - lambda:
lambda n: n * 2: parameters before the colon, the result after it
Step by step, for speak(shout, "Hello"):
stylegets the functionshout, andtextgets"Hello".- Inside,
style(text)calls whatever functionstyleholds:shout("Hello"). - That returns
"HELLO!", whichspeakreturns too.
def shout(text):
return text.upper() + "!"
def whisper(text):
return text.lower() + "..."
def speak(style, text):
return style(text)
print(speak(shout, "Hello"))
print(speak(whisper, "Hello"))A lambda is a tiny function written in one line: lambda n: n * 2 does the same job as the machine below. It has no name and no return: the value of the expression after the colon is what it gives back.
double = lambda n: n * 2
print(double(4))
add = lambda a, b: a + b
print(add(2, 3))Lambdas are most useful handed straight to another function, right where they're needed. The next lessons do exactly that.
def apply_twice(f, x):
return f(f(x))
print(apply_twice(lambda n: n + 3, 10))
print(apply_twice(lambda s: s + "!", "go"))Why pass functions around? It lets one function do many jobs: speak doesn't know or care how to shout or whisper; you choose by handing it the right function. Python's own sorted, max, map and filter (the next lessons) all work this way.
Mistakes and edge cases.
- Calling instead of passing.
speak(shout("hi"), "x")passes the string"HI!", sostyle(text)fails withTypeError: 'str' object is not callable. - return in a lambda.
lambda x: return xgivesSyntaxError: invalid syntax. A lambda holds one expression; its value is returned automatically. - Long lambdas. If it needs an
ifblock or several steps, write a normaldefwith a name. - Printing a function.
print(shout)shows<function shout at 0x...>, not a result.
Quiz
What does this print?
f = lambda x: x * x print(f(5))What does this print?
def twice(f, x): return f(f(x)) print(twice(lambda n: n * 10, 2))What does this print?
def hi(): return "hi" f = hi print(f() + f())Which does the same job as
lambda n: n + 1?- def f(n): return n + 1
- def f(n): print(n + 1)
- def f(): return n + 1
Which line has a mistake?
def shout(text): return text.upper() loud = shout() print(loud("hi"))
Coding tasks
Write
apply(f, x)that calls the functionfonxand returns the result.Make
triplea lambda that gives back its argument times 3.Write
apply_twice(f, x)that callsfonx, then callsfagain on that result, and returns it.