What is the output of the following Python program?
f = lambda: None
g = lambda *args: len(args)
print(f.__name__, f(), g(), g(1, 2, 3))
A lambda keeps the name <lambda> even when assigned. *args works in lambdas too.
Lambda Functions · Exercise 2 of 4
Read each Python program and choose what it prints. Every program was run on Python 3, so the answers are the real output.
What is the output of the following Python program?
f = lambda: None
g = lambda *args: len(args)
print(f.__name__, f(), g(), g(1, 2, 3))
A lambda keeps the name <lambda> even when assigned. *args works in lambdas too.
What is the output of the following Python program?
people = [{"n": "Asha", "age": 30}, {"n": "Ravi", "age": 25}, {"n": "Meera", "age": 28}]
print([p["n"] for p in sorted(people, key=lambda p: p["age"])])
print(max(people, key=lambda p: len(p["n"]))["n"])
Sorted by age 25, 28, 30. The longest name is "Meera" with five letters.
What is the output of the following Python program?
from functools import partial
pow2 = partial(pow, 2)
binary = partial(int, base=2)
print(pow2(10), binary("1011"), binary("1011", base=8))
pow2(10) is pow(2, 10). A keyword frozen by partial can still be overridden: int("1011", base=8) = 521.
What is the output of the following Python program?
x = 10
f = lambda: x
g = lambda x=x: x
x = 20
print(f(), g())
f looks up x when called (20). g's default was evaluated when g was created (10).
What is the output of the following Python program?
add = lambda a: lambda b: a + b
compose = lambda f, g: lambda x: f(g(x))
inc_then_double = compose(lambda x: x * 2, add(1))
print(add(2)(3), list(map(add(10), [1, 2])), inc_then_double(5))
add(2) returns a function waiting for b. compose applies g first: add(1)(5) = 6, then doubles it to 12.
Timed online tests with instant scores and explanations.