🌐
W3Schools
w3schools.com › python › python_recursion.asp
Python Recursion
Python Examples Python Compiler ... Plan Python Interview Q&A Python Bootcamp Python Training ... Recursion is when a function calls itself....
🌐
GeeksforGeeks
geeksforgeeks.org › python › recursion-in-python
Recursion in Python - GeeksforGeeks
Interview Questions · Examples ... Updated : 19 May, 2026 · Recursion is a programming technique where a function calls itself either directly or indirectly to solve a problem....
Published   May 19, 2026
Discussions

Recursion with return statements
I’m having a hard time understanding recursive functions with return statements. I’ve read many other explanations and I’m just not getting it. I’m using the example provided in freeCodeCamp’s Python Tutorial for Beginners (with mini-projects) here with extra print statements to help ... More on discuss.python.org
🌐 discuss.python.org
13
0
October 30, 2024
list - Basics of recursion in Python - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... "Write a recursive function, "listSum" that takes a list of integers and returns the sum of all integers in the list". More on stackoverflow.com
🌐 stackoverflow.com
Python recursion function for newbie
I can’t understand this code. I thought it had to do a loop until it gets to the base number. So, if you start with 6, then result should be 6 + (6 - 1) = 11. But there’s no 11 in the results list. If it’s counting from 0, then the first number should be 1 + (1 -1) = 1, which is in the list. More on discuss.python.org
🌐 discuss.python.org
7
0
May 21, 2023
algorithm - Understanding recursion in Python - Stack Overflow
I'm really trying to wrap my brain around how recursion works and understand recursive algorithms. For example, the code below returns 120 when I enter 5, excuse my ignorance, and I'm just not seei... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Berkeley
pythonnumericalmethods.studentorg.berkeley.edu › notebooks › chapter06.01-Recursive-Functions.html
Recursive Functions — Python Numerical Methods
def factorial(n): """Computes and returns the factorial of n, a positive integer. """ if n == 1: # Base cases! return 1 else: # Recursive step return n * factorial(n - 1) # Recursive call ... WHAT IS HAPPENING? First recall that when Python executes a function, it creates a workspace for the variables that are created in that function, and whenever a function calls another function, it will wait until that function returns an answer before continuing.
🌐
Medium
jasondeden.medium.com › recursive-functions-in-python-a-visual-walk-through-28cf22cc10e2
Recursive Functions in Python — A Visual Walk-Through | by Jason Eden | Medium
November 3, 2021 - Recursive functions in Python, because it is an interpreted language and will run one line of code at a time by default, will finish one “side” of the function completely to the bottom first, and then loop back up, iterating at each point up and down the logical tree until you’ve finished all processing (reached a stop criteria) for all nodes and returned to the root node.
🌐
freeCodeCamp
freecodecamp.org › news › recursion-in-python-intro-for-beginners
Recursion in Python – A Practical Introduction for Beginners
March 12, 2026 - Recursion is when a function solves a problem by calling itself. It sounds odd at first — why would a function call itself? — but once it clicks, you'll find it's often the most natural way to express
🌐
W3Schools
w3schools.com › python › gloss_python_function_recursion.asp
Python Function Recursion
Python Examples Python Compiler ... Python Training ... Python also accepts function recursion, which means a defined function can call itself....
Find elsewhere
🌐
Princeton University
introcs.cs.princeton.edu › python › 23recursion › index.php
Recursion
The idea of calling one function from another immediately suggests the possibility of a function calling itself. The function-call mechanism in Python supports this possibility, which is known as recursion.
🌐
Real Python
realpython.com › python-recursion
Recursion in Python: An Introduction – Real Python
October 21, 2023 - In Python, it’s also possible for a function to call itself! A function that calls itself is said to be recursive, and the technique of employing a recursive function is called recursion.
🌐
Readthedocs
pynote.readthedocs.io › en › latest › FunctionInPy › Recursion.html
Python Recursion — pynotes documentation
Factorial of a number is the product of all the integers from 1 to that number. For example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720. def factorial(x): """This is a recursive function to find the factorial of an integer""" if x == 1: return 1 else: return (x * factorial(x-1)) num = 3 print("The factorial of", num, "is", factorial(num))
🌐
Invent with Python
inventwithpython.com › recursion
The Recursive Book of Recursion - Invent with Python
This book teaches the basics of recursion, exposes the ways it's often poorly taught, and clarifies the fundamental principles behind all recursive algorithms. It is project-based, containing complete, runnable programs in both Python and JavaScript, and covers several common recursive algorithms for tasks like calculating factorials, producing numbers in the Fibonacci sequence, tree traversal, maze solving, binary search, quicksort and merge sort, Karatsuba multiplication, permutations and combinations, and solving the eight queens problem.
🌐
DataCamp
datacamp.com › tutorial › recursion-in-python
Recursion in Python: Concepts, Examples, and Tips | DataCamp
April 9, 2025 - Use recursion when the problem involves breaking it into smaller sub-problems (like tree traversal or calculating factorials) or when the recursive solution is more intuitive and cleaner than iterative alternatives. ... Benito MartinFounder @ Martin Data Solutions | AWS Certified AI & Machine Learning Engineer | Technical Writer | Data Scientist ... 36 hrDevelop your data analytics skills in Python.
🌐
Python.org
discuss.python.org › python help
Recursion with return statements - Python Help - Discussions on Python.org
October 30, 2024 - I’m having a hard time understanding recursive functions with return statements. I’ve read many other explanations and I’m just not getting it. I’m using the example provided in freeCodeCamp’s Python Tutorial for Beginners (with mini-projects) here with extra print statements to help me understand the work flow, but didn’t help much: def add_one(num): print("add_one starting") if (num >= 9): print("num is >= 9") print(num) return num + 1 total = num + 1 p...
Top answer
1 of 5
115

Whenever you face a problem like this, try to express the result of the function with the same function.

In your case, you can get the result by adding the first number with the result of calling the same function with rest of the elements in the list.

For example,

listSum([1, 3, 4, 5, 6]) = 1 + listSum([3, 4, 5, 6])
                         = 1 + (3 + listSum([4, 5, 6]))
                         = 1 + (3 + (4 + listSum([5, 6])))
                         = 1 + (3 + (4 + (5 + listSum([6]))))
                         = 1 + (3 + (4 + (5 + (6 + listSum([])))))

Now, what should be the result of listSum([])? It should be 0. That is called base condition of your recursion. When the base condition is met, the recursion will come to an end. Now, lets try to implement it.

The main thing here is, splitting the list. You can use slicing to do that.

Simple version

>>> def listSum(ls):
...     # Base condition
...     if not ls:
...         return 0
...
...     # First element + result of calling `listsum` with rest of the elements
...     return ls[0] + listSum(ls[1:])
>>> 
>>> listSum([1, 3, 4, 5, 6])
19

Tail Call Recursion

Once you understand how the above recursion works, you can try to make it a little bit better. Now, to find the actual result, we are depending on the value of the previous function also. The return statement cannot immediately return the value till the recursive call returns a result. We can avoid this by, passing the current to the function parameter, like this

>>> def listSum(ls, result):
...     if not ls:
...         return result
...     return listSum(ls[1:], result + ls[0])
... 
>>> listSum([1, 3, 4, 5, 6], 0)
19

Here, we pass what the initial value of the sum to be in the parameters, which is zero in listSum([1, 3, 4, 5, 6], 0). Then, when the base condition is met, we are actually accumulating the sum in the result parameter, so we return it. Now, the last return statement has listSum(ls[1:], result + ls[0]), where we add the first element to the current result and pass it again to the recursive call.

This might be a good time to understand Tail Call. It would not be relevant to Python, as it doesn't do Tail call optimization.


Passing around index version

Now, you might think that we are creating so many intermediate lists. Can I avoid that?

Of course, you can. You just need the index of the item to be processed next. But now, the base condition will be different. Since we are going to be passing index, how will we determine how the entire list has been processed? Well, if the index equals to the length of the list, then we have processed all the elements in it.

>>> def listSum(ls, index, result):
...     # Base condition
...     if index == len(ls):
...         return result
...
...     # Call with next index and add the current element to result
...     return listSum(ls, index + 1, result + ls[index])
... 
>>> listSum([1, 3, 4, 5, 6], 0, 0)
19

Inner function version

If you look at the function definition now, you are passing three parameters to it. Lets say you are going to release this function as an API. Will it be convenient for the users to pass three values, when they actually find the sum of a list?

Nope. What can we do about it? We can create another function, which is local to the actual listSum function and we can pass all the implementation related parameters to it, like this

>>> def listSum(ls):
...
...     def recursion(index, result):
...         if index == len(ls):
...             return result
...         return recursion(index + 1, result + ls[index])
...
...     return recursion(0, 0)
... 
>>> listSum([1, 3, 4, 5, 6])
19

Now, when the listSum is called, it just returns the return value of recursion inner function, which accepts the index and the result parameters. Now we are only passing those values, not the users of listSum. They just have to pass the list to be processed.

In this case, if you observe the parameters, we are not passing ls to recursion but we are using it inside it. ls is accessible inside recursion because of the closure property.


Default parameters version

Now, if you want to keep it simple, without creating an inner function, you can make use of the default parameters, like this

>>> def listSum(ls, index=0, result=0):
...     # Base condition
...     if index == len(ls):
...         return result
...
...     # Call with next index and add the current element to result
...     return listSum(ls, index + 1, result + ls[index])
... 
>>> listSum([1, 3, 4, 5, 6])
19

Now, if the caller doesn't explicitly pass any value, then 0 will be assigned to both index and result.


Recursive Power problem

Now, lets apply the ideas to a different problem. For example, lets try to implement the power(base, exponent) function. It would return the value of base raised to the power exponent.

power(2, 5) = 32
power(5, 2) = 25
power(3, 4) = 81

Now, how can we do this recursively? Let us try to understand how those results are achieved.

power(2, 5) = 2 * 2 * 2 * 2 * 2 = 32
power(5, 2) = 5 * 5             = 25
power(3, 4) = 3 * 3 * 3 * 3     = 81

Hmmm, so we get the idea. The base multiplied to itself, exponent times gives the result. Okay, how do we approach it. Lets try to define the solution with the same function.

power(2, 5) = 2 * power(2, 4)
            = 2 * (2 * power(2, 3))
            = 2 * (2 * (2 * power(2, 2)))
            = 2 * (2 * (2 * (2 * power(2, 1))))

What should be the result if anything raised to power 1? Result will be the same number, right? We got our base condition for our recursion :-)

            = 2 * (2 * (2 * (2 * 2)))
            = 2 * (2 * (2 * 4))
            = 2 * (2 * 8)
            = 2 * 16
            = 32

Alright, lets implement it.

>>> def power(base, exponent):
...     # Base condition, if `exponent` is lesser than or equal to 1, return `base`
...     if exponent <= 1:
...         return base
...
...     return base * power(base, exponent - 1)
... 
>>> power(2, 5)
32
>>> power(5, 2)
25
>>> power(3, 4)
81

Okay, how will be define the Tail call optimized version of it? Lets pass the current result as the parameter to the function itself and return the result when the base condition it met. Let's keep it simple and use the default parameter approach directly.

>>> def power(base, exponent, result=1):
...     # Since we start with `1`, base condition would be exponent reaching 0
...     if exponent <= 0:
...         return result
...
...     return power(base, exponent - 1, result * base)
... 
>>> power(2, 5)
32
>>> power(5, 2)
25
>>> power(3, 4)
81

Now, we reduce the exponent value in every recursive call and multiple result with base and pass it to the recursive power call. We start with the value 1, because we are approaching the problem in reverse. The recursion will happen like this

power(2, 5, 1) = power(2, 4, 1 * 2)
               = power(2, 4, 2)
               = power(2, 3, 2 * 2)
               = power(2, 3, 4)
               = power(2, 2, 4 * 2)
               = power(2, 2, 8)
               = power(2, 1, 8 * 2)
               = power(2, 1, 16)
               = power(2, 0, 16 * 2)
               = power(2, 0, 32)

Since exponent becomes zero, the base condition is met and the result will be returned, so we get 32 :-)

2 of 5
3

Early exit is typical for recursive functions. seq is falsy when empty (therefore when there are no numbers left to sum).

Slice syntax allows to pass sequence to recursively called function without integer consumed in current step.

def listSum(seq):
    if not seq:
        return 0
    return seq[0] + listSum(seq[1:])

print listSum([1,3,4,5,6])  # prints 19
🌐
Codecademy
codecademy.com › learn › learn-recursion-python
Learn Recursion with Python | Codecademy
This course introduces you to the powerful concept of recursion, helping you solve problems by breaking them down into smaller, manageable subproblems. Learn how to apply recursion across different programming languages to create efficient, elegant solutions.
Rating: 4.3 ​ - ​ 67 votes
🌐
Python.org
discuss.python.org › python help
Python recursion function for newbie - Python Help - Discussions on Python.org
May 21, 2023 - I can’t understand this code. I thought it had to do a loop until it gets to the base number. So, if you start with 6, then result should be 6 + (6 - 1) = 11. But there’s no 11 in the results list. If it’s counting from 0, then the first number should be 1 + (1 -1) = 1, which is in the list.
🌐
Programiz
programiz.com › python-programming › recursion
Python Recursion (Recursive Function)
Every recursive function must have a base condition that stops the recursion or else the function calls itself infinitely. The Python interpreter limits the depths of recursion to help avoid infinite recursions, resulting in stack overflows.
Top answer
1 of 4
82

I'm wondering whether you meant "recursive". Here is a simple example of a recursive function to compute the factorial function:

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)

The two key elements of a recursive algorithm are:

  • The termination condition: n == 0
  • The reduction step where the function calls itself with a smaller number each time: factorial(n - 1)
2 of 4
10

Recursion in Python works just as recursion in an other language, with the recursive construct defined in terms of itself:

For example a recursive class could be a binary tree (or any tree):

class tree():
    def __init__(self):
        '''Initialise the tree'''
        self.Data = None
        self.Count = 0
        self.LeftSubtree = None
        self.RightSubtree = None

    def Insert(self, data):
        '''Add an item of data to the tree'''
        if self.Data == None:
            self.Data = data
            self.Count += 1
        elif data < self.Data:
            if self.LeftSubtree == None:
                # tree is a recurive class definition
                self.LeftSubtree = tree()
            # Insert is a recursive function
            self.LeftSubtree.Insert(data)
        elif data == self.Data:
            self.Count += 1
        elif data > self.Data:
            if self.RightSubtree == None:
                self.RightSubtree = tree()
            self.RightSubtree.Insert(data)

if __name__ == '__main__':
    T = tree()
    # The root node
    T.Insert('b')
    # Will be put into the left subtree
    T.Insert('a')
    # Will be put into the right subtree
    T.Insert('c')

As already mentioned a recursive structure must have a termination condition. In this class, it is not so obvious because it only recurses if new elements are added, and only does it a single time extra.

Also worth noting, python by default has a limit to the depth of recursion available, to avoid absorbing all of the computer's memory. On my computer this is 1000. I don't know if this changes depending on hardware, etc. To see yours :

import sys
sys.getrecursionlimit()

and to set it :

import sys #(if you haven't already)
sys.setrecursionlimit()

edit: I can't guarentee that my binary tree is the most efficient design ever. If anyone can improve it, I'd be happy to hear how

🌐
Python Morsels
pythonmorsels.com › what-is-recursion
What is recursion? - Python Morsels
March 11, 2026 - So when factorial was called with 4, Python put a frame on the call stack: And since factorial called factorial again, another frame was added to the call stack: Whenever any function is called, that function call is added to the call stack until that function returns. And each stack frame independently keeps track of its own variables. Once we finally reach the base case in a recursive function, it'll return a value to the stack frame that called it: