Skip to the solution
MediumDSA11 min read

What is the difference between the call stack and the heap in Python?

649 views

The problem

Question presented to candidate: "In languages like C or Java people talk about values on the stack and objects on the heap. How does that map to Python? What lives on the call stack, what lives on the heap, and what consequences does that have for recursion, closures and memory?"

What a strong answer should cover:

  • The call stack is the stack of frames, one per active function call; a frame holds the local variable slots (references), a small evaluation stack, and the position in the bytecode, and is linked to its caller via f_back.
  • Every Python object, including ints and strings, lives on the heap; locals in a frame are only references to heap objects. There is no "value type on the stack" in Python.
  • When a call returns its frame is discarded, but objects it created survive if anything still references them (a return value, a closure cell, a global).
  • The stack is bounded: sys.getrecursionlimit() (1000 by default) raises RecursionError; deep recursion can be converted to a loop with an explicit list as the stack, which lives on the heap.
  • CPython details: since 3.11 frames are cheap internal structures and frame objects are created lazily; generators keep their frame alive between next() calls; tracebacks keep frames and all their locals alive.

Code / implementation expected: Optional β€” walking sys._getframe() up the stack, or showing a recursive function hit RecursionError while an explicit-stack version succeeds.

  • memory
  • stack
  • heap

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

11 min read Β· 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonFrames on the stack, objects on the heap, closures that outlive frames
PythonRecursionError, an explicit heap stack, generator frames and tracebacks

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 77 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

How does functools.lru_cache work?

Continue