10

According to this Python code visualizer, Python strings are allocated on the stack and not on the heap.

Why is this? I thought they would be similar to Java where Strings are allocated on the heap.

asked Feb 27, 2012 at 19:29

2 Answers 2

7

That visualizer is not showing the string data on the stack. It is showing the local references to the heap data as part of the call stack. This is very similar to Java where String references are local variables that point to actual String objects on the heap.

The visualizer is free to make any kind of representation simplification it cares to. It does not imply that "Python strings are allocated on the stack" in any given implementation of Python.

answered Feb 27, 2012 at 23:55
1

Has Greg said in his answer, strings are allocated on the heap.

The visualizer has choosen to display some objects in the "frame" part, which seems wrong to me. Fortunately, it has little impact for someone learning python, since affected objects (int, string) are immutable. So reasoning about effects is still possible.

However it gives the false impression that strings are duplicated in memory when you do things like:

x = "hello"
y = x
answered Oct 10, 2012 at 9:23

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.