Python Recursive and Lambda Functions

In this tutorial you will learn:

  • Recursive Functions in Python
  • Lambda Functions in Python
  • Use of Recursive Functions
  • Use of Lambda Functions

Recursive Functions in Python

These functions call themselves within the function but need a base case to stop the recursion otherwise it would call it self indefinitely. So a base case defines a condition which returns a base value of the function and it allows us to calculate the next value which intern would be used to calculate the next value until we reach to the top most call off the function.

Example:

  1. print("Output Result")
  2. num = 7<br />
  3. def factorial(num):
  4.  if num == 1:
  5.   return 1
  6.  else:
  7.   return num * factorial(num-1)
  8. print("Factorial of 7 is: ", factorial(num))

Another example would be to calculate fibonacci series using recursion

  1. def fibonacci(n):
  2.  if n <= 1:
  3.   return 1
  4.  else:
  5.   return(fibonacci(n-1) + fibonacci(n-2))
  6. print("Output Result of Fib")
  7. print(fibonacci(10), end=" “)

Lambda Functions in Python

There are functions that have no name and they are known as anonymous functions. In Python we can make anonymous functions as well and they are known as lambda functions. Lambda functions in Python are usually small and concise they have all properties of a normal function like we can pass arguments and get the results but we cannot give it a name.

  1. print("Output Result")
  2. rem = lambda num1: num1 % 5
  3. print('Remainder is', rem(24))
Lambda functions with filter function would allow us to filter with a certain criteria. Example below show how to filter numbers in a list that are greater than 4.
  1. list = [5,2,1,0,7,9,18,22, 98]
  2. filter_lambda= filter (lambda x: x > 4, list)
  3. print(list(filter_lambda)) #it will print 5 7 9 18 22 98
Map function applies a certain operation on each element of a list. Let's suppose we want to square a list of numbers one way would be through for loop another way is using map and lambda function as shown in the example.
  1. list = [5,2,1,0]
  2. result = map (lambda num: num*num, list)
  3. print(list(result)) # it will print 25 4 1 0
Reduce is used to reduce a list into a single result by performing some kind of calculation.
  1. list = [5,2,1,0,7,6]
  2. totalSum = reduce((lambda x, y: x + y), list)
  3. print (totalSum) #it will print 21 which is the result of summing all values in a list

Usage of Recursive Functions

Recursive functions are used when a function wants to call it self. They are useful because many times they provide a much simpler and easier to understand solution than iterative function. One good example of a recursive case is traversing directories and files.

Usage of Lambda Functions

We use lambda function when we want to pass function as an argument to a function or when we want a function to live for a very limited time.

Add new comment