I favor recursive solutions when:

  • The implementation of the recursion is much simpler than the iterative solution, usually because it exploits a structural aspect of the problem in a way that the iterative approach cannot

  • I can be reasonably assured that the depth of the recursion will not cause a stack overflow, assuming we're talking about a language that implements recursion this way

Condition 1 doesn't seem to be the case here. The iterative solution is about the same level of complexity, so I'd stick with the iterative route.

Answer from John Feminella on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › loops vs recursion
r/learnpython on Reddit: Loops vs recursion
April 30, 2018 -

So I was watching this video on youtube and was simply amazed by this function to calculate factorials with recursions.

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

Since I'm pretty new to python and coding in general (I'm a lawyer by profession), I would have solved this problem with loops. The moment I understood the concept of this function, I was baffled by the simplicity and beauty of it.

Now here's my question:

  1. In which cases is it smarter to use one or the other and what are the benefits? (if there even is a general rule)

  2. Where can I learn more about recursions? Are there any tutorials online?

Thanks :)

Top answer
1 of 5
36
Every recursive solution can be expressed as a loop, and vice versa. In Python, you use recursion when the recursive solution makes it easier to understand (you would probably use a loop for a factorial) Recursions are heavily used in functional programming (which Python does not excel at), and Guido said he prefers loops instead of recursion. If you like recursion and mathematical elegance in programming, I recommend you take a look at functional programming and functional programming languages. Be advised though that functional programming can be difficult to grasp at first.
2 of 5
20
You CAN solve almost any problem using almost any loop. But when is it more appropriate to use which loop, my opinion is this: A while loop is the correct solution when the data amount and endpoint is unknown. A for loop is the correct solution when the amount of data, and endpoint is known. A Recursion is the correct solution when the amount is known, but the end point is not. So what I mean by that is, imagine finding a file in a bunch of folders. Inside every folder the AMOUNT of files are known, so you use a for loop to walk through the files and you pick out the right file. But how many folders do you need to go through? You don't know that, because every subfolder COULD have another subfolder, or not. And so the folder structure branches out, in an unknown way. This becomes difficult to deal with using multiple for loops. Again, because the endpoint is unknown. Here recursion is the perfect solution. find_file(folder): global filelist for file in folder.files: if ".jpg" in file.name: filelist.append(file) for subfolder in folder.dirs: find_file(subfolder)
Recursion in the real world Apr 28, 2024
r/learnpython
2y ago
I use a lot of for loops in programming May 15, 2022
r/Python
4y ago
What's the point of recursion? Feb 12, 2023
r/learnpython
3y ago
Recursion vs using while loop Aug 20, 2023
r/learnpython
3y ago
More results from reddit.com
🌐
HackerNoon
hackernoon.com › recursion-vs-looping-in-python-9261442f70a5
Recursion vs. Looping in Python | HackerNoon
January 17, 2019 - Recursion occurs when any function calls itself. One of the big differences between recursion and looping is the way that a recursive function terminates. In the above example, a for loop ends at the end of the sequence it is looping over.
Discussions

python - When to use while loops vs recursion - Stack Overflow
I am a beginner and I am beginning to learn about 'while' statement loops to perform iteration. However, earlier on I learned about 'if/else' statements and how one can perform recursion using if/e... More on stackoverflow.com
🌐 stackoverflow.com
code quality - Recursion or while loops - Software Engineering Stack Exchange
If you take the programming language Python, it supports recursion, but by default there is a limit for the recursion depth (1000). If it exceeds the limit, we will get an error or exception. That limit can be changed, but if we do that we may experience abnormal situations in the language. At this time (number of calls more than recursion depth), we need to prefer loop ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
January 11, 2013
python - What's the difference between nested loops, and recursive functions? - Stack Overflow
What's the difference in the output in using a nested loop or a recursive function. Which is the best one for generating combinations while accounting for conditions? More on stackoverflow.com
🌐 stackoverflow.com
Is recursion faster/more efficient than looping?
In some languages in some cases, recursion can be equivalent to tight loops thanks to the tail call optimization. That's not the case in python and recursion is slower than an equivalent flat loop, full stop. That said, certain problems naturally lend themselves to recursive approaches and it makes no sense to avoid a clean and elegant solution only because it's not the fastest possible one. More on reddit.com
🌐 r/learnpython
19
52
September 4, 2016
🌐
Educative
educative.io › answers › what-is-the-difference-between-loops-and-recursion-in-python
What is the difference between loops and recursion in Python?
A recursive function will continually call itself, pushing values and new instances of the function to the stack, which might eventually lead to a Stack Overflow error. In comparison, loops are stored in dynamic memory, where variables can be ...
🌐
Better Programming
betterprogramming.pub › when-to-loop-when-to-recurse-b786ad8977de
When to Loop? When to Recurse?. How to make the most of recursion in… | by Faith Chikwekwe | Better Programming
May 20, 2019 - Cracking the Coding Interview states that “All recursive algorithms can [also] be implemented iteratively…” in its section on approaching technical interview problems using recursion. Solving a Python problem iteratively might include using a for or while loop.
Top answer
1 of 8
213

Recursion is not intrinsically better or worse than loops - each has advantages and disadvantages, and those even depend on the programming language (and implementation).

Technically, iterative loops fit typical computer systems better at the hardware level: at the machine code level, a loop is just a test and a conditional jump, whereas recursion (implemented naively) involves pushing a stack frame, jumping, returning, and popping back from the stack. OTOH, many cases of recursion (especially those that are trivially equivalent to iterative loops) can be written so that the stack push / pop can be avoided; this is possible when the recursive function call is the last thing that happens in the function body before returning, and it's commonly known as a tail call optimization (or tail recursion optimization). A properly tail-call-optimized recursive function is mostly equivalent to an iterative loop at the machine code level.

Another consideration is that iterative loops require destructive state updates, which makes them incompatible with pure (side-effect free) language semantics. This is the reason why pure languages like Haskell do not have loop constructs at all, and many other functional-programming languages either lack them completely or avoid them as much as possible.

The reason why these questions appear so much in interviews, though, is because in order to answer them, you need a thorough understanding of many vital programming concepts - variables, function calls, scope, and of course loops and recursion -, and you have to bring the mental flexibility to the table that allows you to approach a problem from two radically different angles, and move between different manifestations of the same concept.

Experience and research suggest that there is a line between people who have the ability to understand variables, pointers, and recursion, and those who don't. Almost everything else in programming, including frameworks, APIs, programming languages and their edge cases, can be acquired through studying and experience, but if you are unable to develop an intuition for these three core concepts, you are unfit to be a programmer. Translating a simple iterative loop into a recursive version is about the quickest possible way of filtering out the non-programmers - even a rather inexperienced programmer can usually do it in 15 minutes, and it's a very language-agnostic problem, so the candidate can pick a language of their choice instead of stumbling over idiosyncracies.

If you get a question like this in an interview, that's a good sign: it means the prospective employer is looking for people who can program, not people who have memorized a programming tool's manual.

2 of 8
38

It depends.

  • Some problems are very amenable to recursive solutions e.g. quicksort
  • Some languages don't really support recursion e.g. early FORTRANs
  • Some languages assume recursion as a primary means for looping e.g. Haskell

It's also worth noting that support for tail recursion makes tail recursive and iterative loops equivalent, that is, recursion doesn't always have to waste the stack.

Also, a recursive algorithm can always be implemented iteratively by using an explicit stack.

Finally, I'd note that a five-line solution is probably always better than a 100 line one (assuming they are actually equivalent).

Find elsewhere
🌐
Medium
medium.com › hackernoon › recursion-vs-looping-in-python-9261442f70a5
Recursion vs. Looping in Python
January 21, 2019 - Recursion occurs when any function calls itself. One of the big differences between recursion and looping is the way that a recursive function terminates. In the above example, a for loop ends at the end of the sequence it is looping over.
🌐
SSSgram
analyticsinsight.net › home › latest news › recursion or loops? which is better in python!
Recursion or Loops? Which is better in Python!
July 10, 2024 - Recursion provides opportunities for you to come up with elegant solutions to difficult problems, and loops do for regular everyday jobs efficiency and simplicity. Python programmers have an opportunity to comprehend both the powers and the ...
Top answer
1 of 3
1

A recursive algorithm calls a function from within that same function (recursion). Whether to perform the recursion is based on some condition.

    function foo()
    {
            ?/ do work
            if( condition )
                    foo();
    }

An iterative algorithm typically calls a function some number of times (n).

    function foo()
    {}

    for(int i = 0; i < n; i++)
            foo();

A recursive function is typically used when some piece of data needs to be manipulated repeatedly and the condition of whether to repeat is dependent on the previous manipulation. Computing a truncated infinite series in math is an example of this.

An iterative function is typically used when the condition is not dependent on the previous manipulation. Inverting a matrix has a predefined n.

Either method can be used for most purposes, but you will typically find that one is easier than the other for a particular case.

Be aware of callstack overflow with recursion though. It is best to only use it if you can guarantee that the algorithm will converge and end within some number of recursions.

2 of 3
1

Recursion can be seen as "just" another way of doing loops. The main advantage is code readability, as you can see in this Stackoverflow question, in this case when there are a lot of nested loops.

Be careful however, as there is a small recursion limit on Python (1000). You can verify by typing

>>>import sys
>>>print sys.getrecursionlimit()
1000

For an overview of other cases of recursion vs loops, check out this pdf. However, as stated in this Stackoverflow answer, you should stick to a purely iterative scheme on Python.

🌐
Baeldung
baeldung.com › home › core concepts › recursion and looping
Recursion and Looping | Baeldung on Computer Science
March 18, 2024 - So, in this case, we prefer to use recursion than looping. For example, let’s consider the problem of traversing a binary tree in order. Here, we first traverse the left sub-tree. After that, we traverse the root of the tree, and then we traverse the right sub-tree. This is a repetitive problem on a hierarchical data structure, so recursion is more suited than iteration. We should take the coding language as another important parameter. Generally speaking, we can say that Java, C, and Python, have recursion more costly than looping.
🌐
Reddit
reddit.com › r/learnpython › is recursion faster/more efficient than looping?
r/learnpython on Reddit: Is recursion faster/more efficient than looping?
September 4, 2016 -

Just curious. I'm doing the chapter 3 practice from Automate the boring stuff, and my first instinct was to use recursion on the collatz function. I initially had trouble and just made a loop, but I was annoyed and went back and did it with recursion too.

I'm wondering though, which way is more efficient? How do I check? I'm assuming recursion is the better of the two, but is there a way to check?

code with recursion

code with loop and no recursion

🌐
Medium
medium.com › student-technical-community-vit-vellore › loops-vs-recursion-afd1856a662
LOOPS vs RECURSION
December 21, 2020 - Recursion has more expressive power than iterative looping constructs. I say this because a while loop is equivalent to a tail recursive function and recursive functions need not be tail recursive.
Top answer
1 of 1
1

Better is naturally a subjective term. As mentioned in the comments, both run in O(n) time in terms of runtime complexity. However, depending on the details of the language, recursive functions often take up more space in memory.

Specifically, since you seem to be using Python, each recursive call requires a new function call frame, keeping track of that function call's variables. This takes up significantly more space than a simple loop while taking effectively the same amount of time. In fact, to limit your use of deep recursion, Python by default has a recursion depth limit of 1000; aka, you would not be able to calculate the factorial of numbers above 1000 this way.

Generally speaking, which is the better option depends on the language. And loops will almost always take up less if not equal space to a recursive function. However, this doesn't mean that recursion is useless! When it comes to a simple example like the factorial function, recursion is not at all necessary. However when you are building complex data structures or algorithms, recursion is occasionally necessary if not incredibly cleaner in order to write your solution.

Ultimately Recursion and Loops are nearly the same. I prefer to use recursion when

  1. The implementation of the recursive solutions is much simpler than the iterative solution
  2. I can be sure that the recursion won't cause a stack overflow by going too deep into the callstack

Tree Traversal, Graph Traversal, and Sorting are all good examples of places that recursion is likely your best option

🌐
MIT
web.mit.edu › 6.102 › www › sp23 › classes › 11-recursive-data-types › recursion-and-iteration-review.html
6.101 Fall 2022: Recursion and Iteration
For those kinds of problems, it’s more straightforward to express the recursive algorithm directly, letting Python handle the agenda bookkeeping using its call stack. The converse is also true: any function we can write iteratively, with a loop, could also be written recursively.
🌐
Analytics India Magazine
analyticsindiamag.com › home › deep tech › ultimate guide to recursion and iteration in python
How does recursion compare to iteration in Python?
May 26, 2021 - If the limiting criteria are not met, a while loop or a recursive function will never converge and lead to a break in program execution. Since recursion is executed by defining a function, this function can be called whenever required anywhere in the program. Iterative codes must be constructed at the place requirement. Nevertheless, an iterative code set can be generalized by declaring inside a typical Python function (not a recursive function).
🌐
Ars Technica
arstechnica.com › information-technology › 2013 › 04 › recursion-or-while-loops-which-is-better
Recursion or while loops: Which is better? - Ars Technica
April 27, 2013 - Recursion has more expressive power than iterative looping constructs. I say this because a while loop is equivalent to a tail recursive function and recursive functions need not be tail recursive.
🌐
Quora
quora.com › In-Python-which-is-more-efficient-to-use-recursion-or-iteration
In Python, which is more efficient to use: recursion or iteration? - Quora
Answer (1 of 4): I wouldn't say "more efficient", but iteration seems to me to be more pythonic and is the recommended idiom. Guido van Rossum himself has something to say about it: http://neopythonic.blogspot.com/2009/04/tail-recursion-elimination.html Although Python does support recursion (I...
🌐
Invent with Python
inventwithpython.com › recursion › chapter2.html
Chapter 2 - Recursion vs. Iteration
The while loop has a condition, i < 5, that determines whether the program keeps looping. Similarly, the recursive function uses this condition for its recursive case, which causes the function to call itself and execute the Hello, world! to display its code again. For a more real-world example, the following are iterative and recursive functions that return the index of a substring, needle, in a string, haystack. The functions return -1 if the substring isn’t found. This is similar to Python’s find() string method and JavaScript’s indexOf() string method.