Is there a reference/alias/pointer in Python?

Scott David Daniels Scott.Daniels at Acm.Org
Sat Jul 24 21:12:59 CEST 2004

Daniel Eloff wrote:

> ... If I understand this correctly, mutable objects like lists and
> dictionaries function in much the same way (if you assigned it to
> Users['current_users_username']) but when you attempt to modify the
> object through either pointer you end up modifying the underlying object
> and thus the changes will be reflected in both?
> Am I close?
The big trick to understanding python is to think of variables not as
storage, but as names associated with values.  That is often the missing
link in understanding.

     s = "abcd"
     t = "defg"
Think that your local dictionary (which is where your variables live),
will have a pair of entries, one of which associates "s" with a string
object, and another entry associating "t" with another string object.
If you then do:
     s = 12345
"s" in the dictionary is now associated with the object for 12345.
     t = 12345
The "t" entry is also associated with an object representing 12345
(not necessarily the same object, but one that compares equal).
The "variable" for any python object is a simple PyObject * pointer,
and the only operations on that are to replace the pointer with
another pointer.

If you do this:
     s = [1, 2, 3, 4]
     t = [1, 2, 3, 4]
There is no choice, s and t refer to different objects.
The way to see this is to change each of them and check the results:
     s[2] = -1
     t[1] = -2
Now looking at s and t, you can see they are distinct.  If you do:
     s = [1, 2, 3, 4]
     t = s
     s[2] = -1
     t[1] = -2
and then examine s and t, you can see that s and t are the same list.
this can be check with the "is" comparison.
     s is t
is True if (and only if) the PyObject*'s for s and t match.  For
immutable objects, no useful distinction can be made between two objects
which are ==, but there is still a difference between "is" and "==".
"s is t" works a lot like: "id(s) == id(t)".

Hope this explanation helps.

-Scott David Daniels
Scott.Daniels at Acm.Org

More information about the Python-list mailing list