Search...
Python Course Python Tutorial Interview Questions Python Quiz Python Glossary Python Projects Prac
Recursion in Python
Last Updated : 20 Mar, 2025
Recursion involves a function calling itself directly or indirectly to solve a
problem by breaking it down into simpler and more manageable parts. In
Python, recursion is widely used for tasks that can be divided into identical
subtasks.
In Python, a recursive function is defined like any other function, but it
includes a call to itself. The syntax and structure of a recursive function
follow the typical function definition in Python, with the addition of one or
more conditions that lead to the function calling itself.
Basic Example of Recursion:
1 def factorial(n):
2 if n == 0:
3 return 1
4 else:
5 return n * factorial(n-1)
6
7 print(factorial(5))
Output
120
Explanation: The factorial of a number n (denoted as n!) is the product of all
positive integers less than or equal to n. The recursive approach involves the
function calling itself with a decremented value of n until it reaches the base
case of 1.
Let's understand recursion in python deeply:
Table of Content
Base Case and Recursive Case
Types of Recursion in Python
Recursion vs Iteration
Advantages of using recursion
Disadvantages of using recursion
Basic Structure of Recursive Function
def recursive_function(parameters):
if base_case_condition:
return base_result
else:
return recursive_function(modified_parameters)
Base Case and Recursive Case
Base Case: This is the condition under which the recursion stops. It is
crucial to prevent infinite loops and to ensure that each recursive call
reduces the problem in some manner. In the factorial example, the base
case is n == 1.
Recursive Case: This is the part of the function that includes the call to
itself. It must eventually lead to the base case. In the factorial example,
the recursive case is return n * factorial(n-1).
Example:
1 def fibonacci(n):
2 # Base cases
3 if n == 0:
4 return 0
5 elif n == 1:
6 return 1
7 # Recursive case
8 else:
9 return fibonacci(n-1) + fibonacci(n-2)
10
11 # Example usage
12 print(fibonacci(10))
Output
55
Explanation:
Base Cases: If n == 0, the function returns 0. If n == 1, the function returns
1. These two cases are necessary to stop the recursion.
Recursive Case: The function calls itself twice with the decrements of n
(i.e., fibonacci(n-1) and fibonacci(n-2)), summing the results of these calls.
This division into smaller subproblems continues until the base cases are
reached.
Types of Recursion in Python
Recursion can be broadly classified into two types: tail recursion and non-tail
recursion. The main difference between them is related to what happens
after the recursive call.
Tail Recursion: This occurs when the recursive call is the last operation
executed in the function, with no additional work or calculation following
the recursive call. In many programming languages, tail recursion can be
optimized by the compiler into iterative loops to improve performance and
prevent stack overflow.
Non-Tail Recursion: This occurs when there are operations or calculations
that follow the recursive call. This type prevents the compiler or
interpreter from optimizing the recursion into an iteration.
Here is a Python example that demonstrates both tail recursion and non-tail
recursion:
1 def tail_fact(n, acc=1):
2 # Base case
3 if n == 0:
4 return acc
5 # Tail recursive call with an accumulator
6 else:
7 return tail_fact(n-1, acc * n)
8
9 def nontail_fact(n):
10 # Base case
11 if n == 1:
12 return 1
13 # Non-tail recursive call because the multiplication
happens after the call
14 else:
15 return n * nontail_fact(n-1)
16
17 # Example usage
18 print(tail_fact(5))
19 print(nontail_fact(5))
Output
120
120
Recursion vs Iteration
Recursion:
Recursion is often more intuitive and easier to implement when the
problem is naturally recursive, like tree traversals.
It can lead to solutions that are easier to understand compared to iterative
ones.
Iteration:
Iteration involves loops (for, while) to repeat the execution of a block of
code.
It is generally more memory-efficient as it does not involve multiple stack
frames like recursion.
Advantages of using recursion
Simplicity: Recursive code is generally simpler and cleaner, especially for
problems inherently recursive in nature (e.g., tree traversals, dynamic
programming problems).
Reduced Code Length: Recursion can reduce the length of the code since
the repetitive tasks are handled through repeated function calls.
Disadvantages of using recursion
Memory Overhead: Each recursive call adds a new layer to the stack,
which can result in significant memory use, especially for deep recursion.
Performance Issues: Recursive functions may lead to slower responses
due to overheads like function calls and returns.
Risk of Stack Overflow: Excessive recursion can lead to a stack overflow
error if the recursion depth exceeds the stack limit.
Comment More info
Next Article
Campus Training Program Python Inner Functions
Similar Reads
re.subn() in Python
re.subn() method in Python is used to search for a pattern in a string and
replace it with a new substring. It not only performs the replacement but also…
15+ min read
reduce() in Python
The reduce(fun,seq) function is used to apply a particular function passed in its
argument to all of the list elements mentioned in the sequence passed along.…
15+ min read
Python Version History
Python, one of the most popular programming languages today, has a rich
history of development and evolution. From its inception in the late 1980s to i…
15+ min read
Reversing a List in Python
In this article, we are going to explore multiple ways to reverse a list. Python
provides several methods to reverse a list using built-in functions and manual…
15+ min read
How To Fix Recursionerror In Python
In this article, we will elucidate the Recursionerror In Python through examples,
and we will also explore potential approaches to resolve this issue. What is…
15+ min read
re.search() in Python
re.search() method in Python helps to find patterns in strings. It scans through
the entire string and returns the first match it finds. This method is part of…
15+ min read
re.match() in Python
re.match method in Python is used to check if a given pattern matches the
beginning of a string. It’s like searching for a word or pattern at the start of a…
12 min read
Python - Reversing a Tuple
We are given a tuple and our task is to reverse whole tuple. For example, tuple
t = (1, 2, 3, 4, 5) so after reversing the tuple the resultant output should be (5,…
11 min read
Python | sys.setrecursionlimit() method
This sys module provides access to some variables used or maintained by the
interpreter and to functions that interact strongly with the interpreter. It…
9 min read
Python return statement
A return statement is used to end the execution of the function call and it
"returns" the value of the expression following the return keyword to the calle…
15+ min read
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate
Tower, Sector- 136, Noida, Uttar Pradesh
(201305)
Registered Address:
K 061, Tower K, Gulshan Vivante
Apartment, Sector 137, Noida, Gautam
Buddh Nagar, Uttar Pradesh, 201305
Advertise with us
Company Explore Languages DSA Data Science & Web
About Us Job-A-Thon Hiring Python Data Structures ML Technologies
Legal Challenge Java Algorithms Data Science With HTML
Privacy Policy GfG Weekly C++ DSA for Beginners Python CSS
Careers Contest PHP Basic DSA Data Science For JavaScript
In Media Offline Classroom GoLang Problems Beginner TypeScript
Contact Us Program SQL DSA Roadmap Machine Learning ReactJS
GfG Corporate DSA in JAVA/C++ R Language DSA Interview ML Maths NextJS
Solution Master System Android Tutorial Questions Data Visualisation NodeJs
Placement Design Competitive Pandas Bootstrap
Training Program Master CP Programming NumPy Tailwind CSS
GeeksforGeeks NLP
Videos Deep Learning
Python Computer DevOps System Design School Databases
Tutorial Science Git High Level Design Subjects SQL
Python GATE CS Notes AWS Low Level Design Mathematics MYSQL
Programming Operating Systems Docker UML Diagrams Physics PostgreSQL
Examples Computer Kubernetes Interview Guide Chemistry PL/SQL
Django Tutorial Network Azure Design Patterns Biology MongoDB
Python Projects Database GCP OOAD Social Science
Python Tkinter Management DevOps Roadmap System Design English Grammar
Web Scraping System Bootcamp
OpenCV Tutorial Software Interview
Python Interview Engineering Questions
Question Digital Logic
Design
Engineering Maths
Preparation More Tutorials Machine Programming Clouds/ GATE 2026
Corner Software Learning/Data Languages Devops GATE CS Rank
Development Booster
Company-Wise Science C Programming DevOps
Recruitment Software Testing with Data Engineering GATE DA Rank
Complete Machine
Process Product Structures AWS Solutions Booster
Learning & Data
Aptitude Management C++ Programming Architect GATE CS & IT
Science Program -
Preparation Project Course Certification Course - 2026
[LIVE]
Puzzles Management Java Programming Salesforce GATE DA Course
Data Analytics
Company-Wise Linux Course Certified 2026
Training using
Preparation Excel Python Full Course Administrator GATE Rank
Excel, SQL, Python
All Cheat Sheets Course Predictor
& PowerBI - [LIVE]
Data Science
Training Program -
[LIVE]
Data Science
Course with IBM
Certification
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved