add = lambda a, b : a + b
print(add(10, 20))
Lambda functions are very convenient when we want to perform some simple operations that do not require complex logic. They allow entire function definition to be accomplished in just a single line.
A lambda function is made up of two three parts:
- The
lambda
keyword - Comma separated arguments.
- A single expression.
The arguments are separated from the expression by a colon. Thus the basic syntax is as shown below:
lambda arg1, arg2, arg3, ... : expression
A lambda
function can have many arguments but only a single expression. The expression can be thought of as the body of the lambda
function.
We do not need to explicitly use the return
statement, this is because lambda
functions automatically returns the result after evaluating the expression.
If we want to add two numbers a
and b
, we will take the two numbers as the argument, then in the expression we will define the addition operation.
a lambda function to add two numbers
add = lambda a, b : a + b
print(add(10, 20))
print(add(20, 30))
print(add(50, 100))
In the above example, we have created a lambda function for adding two numbers. Note that lambda
functions do not have a definition name like regular function, we therefore had to assign it to a variable called add
in order to re-use it.
The regular function that is equivalent to the above lambda function is shown below:
def add(a, b):
return a + b
print(add(10, 20))
As clearly shown, the lambda
version is more concise than the regular version as the entire lambda
function is written in a single line.
with formatted output
We can format the output so that the output is more more visually appealing instead of simply returning the result of adding the two numbers.
In the formatted version we will return a string in the form of "a + b = result"
where a
and b
are the two operands and result
is their sum.
formatted version
add = lambda a, b : f"{a} + {b} = {a + b}"
print(add(10, 20))
print(add(40, 70))
In the above example, we are returning a formatted string, the f before the string is used to create f-strings. f-strings are useful when we want to directly include variables and expressions in the string. In an f-string, the expressions inside curly braces {} are first evaluated before they string is fully formed.