Python 3D Academyবাংলা

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"):

  1. style gets the function shout, and text gets "Hello".
  2. Inside, style(text) calls whatever function style holds: shout("Hello").
  3. That returns "HELLO!", which speak returns 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!", so style(text) fails with TypeError: 'str' object is not callable.
  • return in a lambda. lambda x: return x gives SyntaxError: invalid syntax. A lambda holds one expression; its value is returned automatically.
  • Long lambdas. If it needs an if block or several steps, write a normal def with a name.
  • Printing a function. print(shout) shows <function shout at 0x...>, not a result.

Quiz

  1. What does this print?

    f = lambda x: x * x
    print(f(5))
  2. What does this print?

    def twice(f, x):
        return f(f(x))
    
    print(twice(lambda n: n * 10, 2))
  3. What does this print?

    def hi():
        return "hi"
    
    f = hi
    print(f() + f())
  4. 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
  5. Which line has a mistake?

    def shout(text):
        return text.upper()
    
    loud = shout()
    print(loud("hi"))

Coding tasks

  1. Write apply(f, x) that calls the function f on x and returns the result.

  2. Make triple a lambda that gives back its argument times 3.

  3. Write apply_twice(f, x) that calls f on x, then calls f again on that result, and returns it.