A loop or a recursion?

CarBOn report abuse

What is a more correct way of doing something in Python if this can be done both by looping and by recursion?

Answers

srSikh report abuse

Generally, loops are more efficient. This is because each recursion call creates an item in the memory stack. There also can be a limit for the number of recursion calls, and when you exceed this number, you will get a runtime error. So, if you can to achieve a goal with the loop it is better to use them.

CarBOn report abuse

Ok, but why then we need recursions at all if they are less effective than simple iterations?

srSikh report abuse

There are some cases where it is hard to do something with a loop, but it is more readable and convenient to do it with recursion. If the performance is not the key point for your task, and also you know beforehand that there will not be a very deep stack of recursion calls, you are free to use recursion.

CarBOn report abuse

Thanks

Add Answer

Need support?

Just drop us an email to ... Show more