If you need help reviewing Lambda Expressions, take a look at these resources:
Each question has a "Toggle Solution" button -- click it to reveal that question's solution.
What are some differences between
def statements and
Some differences between lambdas and def statements include:
- lambdas are expressions (they are a value), while defs are statements.
- lambdas can only be one liners
- lambdas are anonymous — they have no intrinsic names
What are the intrinsic names of the following functions?
def cube(x): return x * x * x square = lambda x: x * x
The first function has an intrinsic name of
cube. The second function
does not have an intrinsic name, since it is a lambda. Note that
the intrinsic name is the name you should write in your environment
What would Python print?
>>> lambda x: x * x ______<function <lambda > at ...> >>> g = lambda x: x**2' >>> g(4) ______16 >>> (lambda x, y: x * y)(4, 5) ______20
Translate the following def statements into lambda expressions.
# 1 def square(x): return x * x # 2 def compose(f, g): def h(x): return f(g(x)) return h
# 1 square = lambda x: x * x # 2 compose = lambda f, g: lambda x: f(g(x))
Translate the following lambda expressions into def statements.
# 1 pow = lambda x, y: x**y # 2 foo = lambda x: lambda y: lambda z: x + y * z
# 1 def pow(x, y): return x**y # 2 def foo(x): def f(y): def g(z): return x + y * z return g return f
square = lambda x: x * x higher = lambda f: lambda y: f(f(y)) higher(square)(5)
a = (lambda f, a: f(a))(lambda b: b * b, 2)