The lambda
keyword creates an inline function that contains a single expression. The value of this expression is what the function returns when invoked.
Consider the function:
def greeting():
return "Hello"
which, when called as:
print(greeting())
prints:
Hello
This can be written as a lambda function as follows:
greet_me = lambda: "Hello"
See note at the bottom of this section regarding the assignment of lambdas to variables. Generally, don’t do it.
This creates an inline function with the name greet_me
that returns Hello
. Note that you don’t write return
when creating a function with lambda. The value after :
is automatically returned.
Once assigned to a variable, it can be used just like a regular function:
print(greet_me())
prints:
Hello
lambda
s can take arguments, too:
strip_and_upper_case = lambda s: s.strip().upper()
strip_and_upper_case(" Hello ")
returns the string:
HELLO
They can also take arbitrary number of arguments / keyword arguments, like normal functions.