Lambda Expressions
- Expressions that evaluate to a function.
- We can directly assign a name to a function without defining it in our frame with
def
- We can directly assign a name to a function without defining it in our frame with
1
2
3
4
x = 10
square = x * x # This expression evaluates to a number
square = lambda x : x * x # This expression evaluates to a function
square(10)
1
121
- Lambda syntax:
lambda <formal parameter> : <return value>
- “A function with formal parameter that returns the value of return value.”
- The lambda expression is limited to only have a single expression as its return value.
- Cannot have any additional statements.
Lambda Expressions Versus Def Statements
Lambda | Both | Def |
---|---|---|
square = lambda x: x * x | def square(x): return x * x | |
First creates a function with no name, then an assignment statement binds the function to the name | Same parent (frame in which they were defined) | Both binding and function creation happens as a byproduct of def statement (intrinsic naming) |
- Hence, the environmental diagrams for lambda functions and def statements are different.
- Instead of writing a name for the lambda, we denote the function and the frame name as “λ”.
- However, names can still be bound to the function within a frame.