Recursion Limits and Tail Recursion
Explore Python's recursion mechanics including recursion depth limits and why recursion is less efficient than looping. Understand tail recursion as the last executed function call and why Python lacks automatic tail call optimization. Discover when to prefer loops over recursion for performance.
We'll cover the following...
Multiple function calls
Recursion is relatively inefficient compared to looping. This is because each step in a recursion results in a function call, whereas each step in a loop merely requires a “jump” to a different place in the code.
Calling a function involves considerably more work than a simple jump, and, in any system, it is going to take more time and use extra memory (memory is required to store the current state of the function – the values of its local variables – each time the function calls itself recursively).
Limit on recursive calls
However, Python has a rather more immediate problem. Recursive calls are limited to a depth of ...