A loop or a recursion?
What is a more correct way of doing something in Python if this can be done both by looping and by recursion?
What is a more correct way of doing something in Python if this can be done both by looping and by recursion?
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.
Ok, but why then we need recursions at all if they are less effective than simple iterations?
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.
Thanks
Just drop us an email to ... Show more