Search code examples
pythoncopyimmutable-collections

Why does Online Python Tutor present this immutable integer as two different integers graphically?


In Fluent Python, By Luciano Ramalho, Chapter 8, Copies Are Shallow by Default, there is an example:

>>> listOne = [3, [55, 44], (7, 8, 9)]
>>> listTwo = list(listOne)
>>> listTwo
[3, [55, 44], (7, 8, 9)]
>>> listTwo == listOne
True
>>> listTwo is listOne
False

The author suggests that we should run through this code using Online Python Tutor to see what is happening step by step.

I executed the first two lines using Online Python Tutor, and this is the screen shot I got:

enter image description here

What confuses me is:

All three elements from the each list, the immutable integer, the list and the tuple are actually the same, e.g.

listOne[0] is listTwo[0] #True
listOne[1] is listTwo[1] #True
listOne[2] is listTwo[2] #True

So why the graph shows two separate 3s at the beginning of their respective list?


Solution

  • The developers of OnlinePythonTutor made this decision, documented under Unsupported features, because this is not a guaranteed language feature, but instead is implementation specific:

    Python

    for strings and numbers, you can't rely on the behaviors of id() or is matching CPython on your computer; when teaching beginners, you shouldn't rely on these behaviors since they are implementation-specific optimizations. for details, see GitHub issues here and here and here

    You can see from issue 255 the behaviour used to be different for integers, even outside the -5 to 256 range.