Tail Recursion - Bad Practice

suggest change

When the only thing returned from a function is a recursive call, it is refered to as tail recursion.

Here’s an example countdown written using tail recursion:

def countdown(n):
    if n == 0:
        print "Blastoff!"
    else:
        print n
        countdown(n-1)

Any computation that can be made using iteration can also be made using recursion. Here is a version of find_max written using tail recursion:

def find_max(seq, max_so_far):
    if not seq:
        return max_so_far
    if max_so_far < seq[0]:
        return find_max(seq[1:], seq[0])
    else:
        return find_max(seq[1:], max_so_far)

Tail recursion is considered a bad practice in Python, since the Python compiler does not handle optimization for tail recursive calls. The recursive solution in cases like this use more system resources than the equivalent iterative solution.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents