Changing argument value

Stargaming stargaming at gmail.com
Fri Dec 14 10:08:32 EST 2007


On Thu, 13 Dec 2007 22:52:56 +0100, Bruno Desthuilliers wrote:

> flyfree a écrit :
[snip]
>> What is the difference between "y = [3,4]" and "y[0]=3 y[1] =4 "
> 
> In the first case, you rebind the local name y to a new list object -
> and since the name is local, rebinding it only affects the local
> namespace. In the second case, you mutate the list object (bound to the
> local name y) passed to the function. The point to remember is that in
> Python, all variables are references to objects, but names (including
> params) are local.
> 
> HTH

Even though you have the assignment operator *in both cases*, it does 
**not** issue the same thing. 

As Bruno pointed out, in the first case ``y = [3,4]`` it is *rebinding* 
the name `y`. When used with slice notation, the assignment operator 
tells the object bound to y, "Hey, change your item with name/number 0 to 
3, please." This can succeed but it doesn't have to. Raw assignments 
always succeed.

(You could also make assignments of y[0] result in whatever you want, a 
SystemExit for example; not so with pure assignments of y! The behaviour 
of assignments cannot be influenced in any way.)

If you're interested in the special methods Python uses there, `Emulating 
container types <http://docs.python.org/ref/sequence-
types.html#l2h-232>`_ might be interesting for you.

To sum up, the assignment operator has multiple meanings depending on its 
left-hand-side operand.

HTH,



More information about the Python-list mailing list