TDS Archive

An archive of data science, data analytics, data engineering, machine learning, and artificial…

Follow publication

Member-only story

Python Stack Frames and Tail-Call Optimization

Reza Bagheri
TDS Archive
Published in
24 min readApr 24, 2020

Recursion in computer science is a method of problem-solving in which a function calls itself from within its own code. This method is very useful and can be applied to many types of problems, however, it has a limitation. Functions use the stack to keep their local variables, and the stack has a limited size. So if the recursion is too deep you will eventually run out of stack space which is called a stack overflow. However, some compilers implement tail-call optimization, allowing unlimited recursion to occur without stack overflow. In this article, I will first talk about the Python stack frames, and then I will explain the concept of tail-call optimization and show you how it can be implemented in Python.

Stack Frames

Stack is a data structure with a LIFO (Last In First Out) order which has two principal operations:

  • push: adds an element to the stack
  • pop: removes the most recently added element

So the last element added or pushed to the stack is the first element to be removed or popped. The advantage of using the stack to store data is that memory is managed for you. Reading from and writing to stack is very fast, however, the size of the stack…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

TDS Archive
TDS Archive

Published in TDS Archive

An archive of data science, data analytics, data engineering, machine learning, and artificial intelligence writing from the former Towards Data Science Medium publication.

Responses (1)

Write a response