A function without a name is called an Anonymous Function. Python also supports creating anonymous functions which are also called lambda function in python.
Normal functions in python are defined using
def. However, anonymous functions are defined using the
lambda keyword which why also known as lambda functions.
Let’s understand this by comparing examples of a regular function and a lambda function.
def cube(x): return x*x*x result = cube(2) print("Cube of the number is", result)
Now, we know the output of the above code is 8 and we also know that we want to use this function only once in the complete code. Instead of writing multiple lines, we can write a single line of code where we want to use it.
Syntax for a lambda function is
lambda argument : expression and we’ll write the above in the same format.
cube = lambda x : x * x * x result = cube(2) print("Cube of the number is", result)
Let’s check another example with two arguments.
x = lambda a,b : a + b result = x(3, 4) print("Sum is", result)
Sum is 7
These were some basic examples for Anonymous/Lambda function in python. we’ll learn and use more of these in the coming tutorials.