On Sep 9, 1:59 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> 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

This means that x now points to the value of x + 1, i.e. an int object
with value 4.

> >>> print x == y # of course, they are pointers to the same value

Of course not, now x points to 4 and y points to 3 !

> 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)

Let's see what happens here:  when lower_string(s) is called, the 's'
which is local to lower_string is made to point to the same object as
the global s (i.e. the string object with value "STRING").  In the
body of the function, the statement s=s.lower() makes the local 's'
point to a new string object returned s.lower().  Of course this has
not effect on what object the global 's' points to.

> >>> print s == "string"

Obviously not, since s still points to the string object with value
"STRING"

> False
>
> The "names in Python are pointers" analogy only gives you the right
> answer half the time.

They give *you* the right answer only half the time ;)

They give me the right answer all the time.  Not that I usually think
of names as pointers.  But if I choose to do so, I can still get it
right.  And if it works for me consistently, there must be some
validity in it, no?

What I think is a more dangerous misconception is to think that the
assignement operator (=) has the same meaning in C and python.

--
Arnaud

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to