unexpected behavior: did i create a pointer?
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Sun Sep 9 08:59:41 EDT 2007
On Sun, 09 Sep 2007 02:30:00 -0700, Arnaud Delobelle wrote:
>> You know, maybe because I came to Python with no C experience, I never
>> had trouble with the "unexpected behaviour" that so confused the
>> original poster. It's just obvious.
>
> The funny thing is that if the OP had thought of both 'a' and 'copyOfA'
> as C-like pointers then he wouldn't have been confused :)
You're almost certainly wrong. He would have written to ask why this
doesn't do what he expects:
>>> x = 3
>>> y = x # x and y are both pointers to the same value
>>> x += 1
>>> print x == y # of course, they are pointers to the same value
False
Or why lower_list() works as expected, but lower_string() doesn't:
>>> def lower_list(L):
... for i, x in enumerate(L):
... L[i] = x.lower()
...
>>> s = ['STRING']
>>> lower_list(s)
>>> print s == ['string']
True
>>>
>>> def lower_string(s):
... s = s.lower()
...
>>> s = "STRING"
>>> lower_string(s)
>>> print s == "string"
False
The "names in Python are pointers" analogy only gives you the right
answer half the time. The "names in Python are names" analogy gives you
the right answer ALL THE TIME, no exceptions.
--
Steven.
More information about the Python-list
mailing list