Open In App

When not to use Recursion while Programming in Python?

Last Updated : 26 Dec, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

To recurse or not to recurse, that is the question. We all know about the fun we have with recursive functions. But it has its own set of demerits too, one of which is going to be explained in this article to help you choose wisely.

Say, we need to create a function which when called needs to print the data in a linked list.

This can be done in 2 ways:

  • 1. With Recursion
  • 2. Without Recursion

1. With Recursion:

```
def print_linkedlist(head):

   if head is not None:
       print(head.data)
       print_linkedlist(head.next)
```

The first approach works too but if the list really long like around 1000 elements then the program will hit recursion depth and errors out. Not to forget that as the list length increases, the stack size increases linearly too.

What is Recursion Depth?

Before we go ahead, you ought to know that this problem is Python-specific. There are languages where we don’t encounter this problem but that’s not going to be discussed here.  We know that a recursive function calls itself. This means that a new function is called within the original function. Assume a linked list counting from 0 to n by 1 using the recursive code mentioned above.

The first function looks at the head node’s data in the list and then prints it. But the first function hasn’t ended yet. An old function cannot end until all the functions inside it have ended. If we observe the call stack which has the list of currently running functions:  

# the first function waiting for
# innermost functions to end
print_linkedlist()

       # the child function called 
       # within the first function
           print_linkedlist()

The call stack keeps on increasing as the older functions never end because they are waiting for the inner child functions to end. Ultimately, the call stack looks like:

# original Function
print_linkedlist()

  # first level function
  print_linkedlist()
  
    # second level function
    print_linkedlist()
    
      # third level function
      print_linkedlist()
        ……
          ……
            ……
            
              # 1000 level function – Maximum 
              # Recursion Depth Reached
              print_linkedlist()

And BAMMM!!!!! MAXIMUM RECURSION DEPTH!!

A recursion depth counts the number of active layers inside the recursive function. In Python, the default maximum recursive depth limit is 1000. The limit helps prevent stack overflow which is caused by infinite recursion.

Therefore, the second approach like the below is better as the stack size remains constant.

2.  Without Recursion/ Iteration:

```
def print_linkedlist(node):
   while node:
       print(node.data)
       node=node.next
```

Conclusion

Recursion is fun to use but you should understand when to and when not to use it. Some languages like Scala and Haskell support an interesting feature called TAIL CALL RECURSION which prevents the problem of recursion depth by ending the previous function’s call when a new call is made. But Python doesn’t support this feature. So, at least in Python, prefer the iterative approach if you think the function may hit the recursion limit.


Similar Reads

How to use while True in Python
In this article, we will discuss how to use while True in Python. While loop is used to execute a block of code repeatedly until given boolean condition evaluated to False. If we write while True then the loop will run forever. Example: While Loop with True C/C++ Code # Python program to demonstrate # while loop with True while True: pass If we run
2 min read
Hello World Program : First program while learning Programming
In this article, I'll show you how to create your first Hello World computer program in various languages. Along with the program, comments are provided to help you better understand the terms and keywords used in theLearning program. Programming can be simplified as follows: Write the program in a text editor and save it with the correct extension
6 min read
How to not get caught while web scraping ?
In this article, we are going to discuss how to not get caught while web scraping. Let's look at all such alternatives in detail: Robots.txtIt is a text file created by the webmaster which tells the search engine crawlers which pages are allowed to be crawled by the bot, so it is better to respect robots.txt before scraping.Example: Here GFG's robo
5 min read
Python | Delete items from dictionary while iterating
A dictionary in Python is an ordered collection of data values. Unlike other Data Types that hold only a single value as an element, a dictionary holds the key: value pairs. Dictionary keys must be unique and must be of an immutable data type such as a: string, integer or tuple. Note: In Python 2 dictionary keys were unordered. As of Python 3, they
3 min read
Python | Avoiding quotes while printing strings
We often come across small issues that turn out to be big. While coding, the small tasks become sometimes tedious when not handled well. One of those tasks is output formatting in which we require to omit the quotes while printing any list elements using Python. Example Input : ['Geeks', 'For', 'Geeks'] Output : Geeks For GeeksAvoiding Quotes While
4 min read
Decrement in While Loop in Python
A loop is an iterative control structure capable of directing the flow of the program based on the authenticity of a condition. Such structures are required for the automation of tasks. There are 2 types of loops presenting the Python programming language, which are: for loopwhile loop This article will see how to decrement in while loop in Python.
3 min read
Python Do While Loops
In Python, there is no construct defined for do while loop. Python loops only include for loop and while loop but we can modify the while loop to work as do while as in any other languages such as C++ and Java. In Python, we can simulate the behavior of a do-while loop using a while loop with a condition that is initially True and then break out of
3 min read
Difference between for loop and while loop in Python
In this article, we will learn about the difference between for loop and a while loop in Python. In Python, there are two types of loops available which are 'for loop' and 'while loop'. The loop is a set of statements that are used to execute a set of statements more than one time. For example, if we want to print "Hello world" 100 times then we ha
4 min read
Python While Loop
Python While Loop is used to execute a block of statements repeatedly until a given condition is satisfied. When the condition becomes false, the line immediately after the loop in the program is executed. Syntax of while loop in Pythonwhile expression: statement(s)Flowchart of Python While Loop While loop falls under the category of indefinite ite
7 min read
Python While Else
Python is easy to understand and a robust programming language that comes with lots of features. It offers various control flow statements that are slightly different from those in other programming languages. The "while-else" loop is one of these unique constructs. In this article, we will discuss the "while-else" loop in detail with examples. Wha
6 min read
Practice Tags :
three90RightbarBannerImg