Master Python Recursion: Limits, Pitfalls, and Practical Examples
This article explains how recursion works in Python, demonstrates factorial and list‑flattening implementations, shows how to check and adjust the language's recursion limit, and warns about infinite recursion errors with clear code samples.
Recursion is a fundamental concept in mathematics and computer science where a function calls itself to solve smaller instances of a problem.
In Python, recursive functions can easily lead to infinite loops that freeze applications, so developers must ensure there is a way to break out of such loops.
A classic example is the factorial function, which multiplies a number by the factorial of the number minus one until it reaches zero.
# factorial.py
def factorial(number):
if number == 0:
return 1
else:
return number * factorial(number-1)
if __name__ == '__main__':
print(factorial(3))
print(factorial(5))The function can be extended to count how many recursive calls are made:
# factorial with recursion counter
def factorial(number, recursed=0):
if number == 0:
return 1
else:
print('Recursed {} time(s)'.format(recursed))
recursed += 1
return number * factorial(number-1, recursed)
if __name__ == '__main__':
print(factorial(3))Python imposes a recursion depth limit (default 1000) to prevent runaway recursion. You can view and modify this limit using the sys module:
import sys
sys.getrecursionlimit() # returns 1000
# sys.setrecursionlimit(new_limit) to change itExceeding the limit triggers a RuntimeError: maximum recursion depth exceeded exception, as shown by this deliberately bad example:
# bad_recursion.py
def recursive():
recursive()
if __name__ == '__main__':
recursive()Beyond factorials, recursion can be used to flatten nested lists:
# flatten.py
def flatten(a_list, flat_list=None):
if flat_list is None:
flat_list = []
for item in a_list:
if isinstance(item, list):
flatten(item, flat_list)
else:
flat_list.append(item)
return flat_list
if __name__ == '__main__':
nested = [1, 2, 3, [4, 5], 6]
x = flatten(nested)
print(x)Running this code produces a single flat list of integers, demonstrating another practical use of recursion.
In summary, Python’s built‑in recursion limit helps protect developers from poorly designed recursive functions. While recursion can solve many problems, Python offers alternative approaches that are often simpler to debug and maintain.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
21CTO
21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
