Confusion: assignments create object references.

Havens, Peter Peter.Havens at Level3.com
Fri Apr 11 18:28:42 CEST 2003


I am confused about when assignments create references to objects as opposed to copying the value of those objects. I realize this is probably a very common bit of confusion, but I haven't had much luck finding anything in the Python FAQ, from googling the comp.lang.python news group (voluminous thread tangents), or from the regular documentation I've read which has only fueled my confusion. To wit, I read the following "rule" in the O'Reilly book "Learning Python": 

"...Python assignment stores references to objects in names or data structure slots. It always creates references to objects, instead of copying objects."

That seems fairly straight forward. So, I ran this test:

>>> L = [0,1,2]
>>> M = L
>>> L
[0, 1, 2]
>>> M[0] = 9
>>> L[0]
9
>>>

So far so good. This works as I would expect given the rule above.

>>> L = 0
>>> M = L
>>> L
0
>>> M = 1
>>> L
1
>>>

However, I can't wrap my head around this. It seems to violate the rule above. The value in L seems to have been copied. What did I miss? What's the real rule about assignments? Are exceptions to the rule somehow made for certain types of assignments? Also, how do I explicitly create a reference to these types of objects since they appear to be copies? In Perl I would do something like this:

my $M;
my $M_reference = \$M;

Is there an equivalent in Python? I couldn't find a helper function.

Any help would be appreciated. Thanks,
Pete





More information about the Python-list mailing list