Learntofish's Blog

A blog about math, physics and computer science

Archive for April, 2013

Visualizing references and objects in Python

Posted by Ed on April 2, 2013

Pythontutor is a website that lets you visualize your Python code.

For instance, type the following Python code into the window:

x = [1, 2, 3]

# reference to the object that x points to
y = x

# create a copy of the list [1,2,3] and store its address at z
z = x[:]

# create a copy of the list [1,2,3] and store its address at z
a = x.copy()

# reference to the object that z points to
a = z

Then, change from Python 2.7 to Python 3.3 in the drop down menu below the window and click the button Visualize Execution.
Click on forward to process the code and observe how the graphics changes on the right.
Pretty neat, isn’t it!

You can also change some settings such as choosing between Python 2.7 and Python 3.3 and using the address id instead of the arrows.
Change the following settings:
inline primitives and nested object -> render all objects on the heap
draw references using arrows -> use text labels for references

Then, paste the following code into the window:

myString = "hello"

# observe how the id changes
myString += " world"

Observe how the id changes if you try to append the string " world" to myString.
That is because strings are immutable in Python such that Python first creates the new string object "hello world".
The addess of this new object is then assigned to the reference myString.


Posted in computer science | Tagged: , , , | Leave a Comment »