I read that "everything is a reference in python".
Though, when I run in Python Tutor the following code:
lst = [1,[1]]
lst[1]
is drawn as an arrow pointing to a list while lst[0]
is just the number 1
.
I also understand that what makes the difference is that lst[0]
is immutable and lst[1]
is mutable. I still don't get how to explain the drawing in Python Tutor, or any other explanation.
The drawing in Python Tutor looks as if the number itself is saved in lst[0]
and not a reference, but I guess this is wrong because "everything in python is a reference".
How can we explain the drawing otherwise? Is the drawing in Python Tutor misleading and there is actually an address stored in lst[0]
?
CodePudding user response:
Yes, you're right: there is an address stored in lst[0]
, the address of a Python object of type int
, representing the integer 1.
That's literally true in CPython (the "standard" C implementation of Python), but other implementations may use other means.
By convention, diagrams usually show arrows only for "container" objects, which are objects that contain other objects (lists, sets, tuples, dicts, ...). "Scalar" types, which do not contain other objects (ints, floats, bools, ...), are typically shown by displaying a human-readable string naming the value the object represents. Nevertheless, container objects never contain scalar objects directly - they store instead pointers to the Python objects implementing the scalar objects.