Python - Recursive Lambda Function
Add Two Numbers using Lambda Function in Python
In this tutorial, you are going to learn how to define a lambda function that calls itself, i.e., a recursive lambda function in Python.
To demonstrate how we can define a recursive lambda function, we are going to take an example scenario and build on that. And the example scenario is - Factorial of a number.
Yeah! We are going to define a lambda function that find the factorial of a given number, using recursion.
If you remember how to find the factorial of a number using recursion, the code is like you return n*factorial(n-1)
if the the number n
is greater than 1
, or just 1
if the number is 1
. Of course, we named the function as factorial.
In the above description, you may observe that there is an if else stuff that we need to incorporate in our lambda function. So, we are going to use if else in our lambda function.
Now, let us define the lambda function.
Let us assign this lambda function to a variable named factorial
.
We know that the lambda function starts with the lambda keyword.
factorial = lambda
This lambda function must have one parameter, for the input number, whose factorial we are going to find. Let us assume that this number is n
.
factorial = lambda n
The lambda function must return n*factorial(n-1)
if the the number n
is greater than 1
.
factorial = lambda n: n*factorial(n-1) if n>1
Also, the lambda function must return 1
if the the number n
is is 1
.
factorial = lambda n: n*factorial(n-1) if n>1 else 1
Here it is! Our lambda function that can take a number, and return its factorial using recursion technique.
Examples
1. Find the factorial of 5 using recursive lambda function
In this example, we shall use the lambda function that we defined above, and find the factorial of 5.
Python Program
factorial = lambda n: n*factorial(n-1) if n>1 else 1
n = 5
result = factorial(n)
print(f"Factorial of {n} is {result}.")
Output
Factorial of 5 is 120.
Summary
In this tutorial, we learned how to define a recursive lambda function and we have used an example scenario of using the recursive lambda function.