Changing argument value
Bruno Desthuilliers
bdesth.quelquechose at free.quelquepart.fr
Thu Dec 13 16:52:56 EST 2007
flyfree a écrit :
>>>>def fooA(y):
>
> y = [3,4]
> return y
>
>
>>>>def fooB(y):
>
> y[0] = 3
> y[1] = 4
> return y
>
>
>>>>x = [1,2]
>>>>fooA(x)
>
> [3, 4]
>
>>>>x
>
> [1, 2]
>
>
>>>>fooB(x)
>
> [3, 4]
>
>>>>x
>
> [3, 4]
> ===============
>
> From above, the original argument value of fooA is same as before
> [1,2]
> but the original argument value of fooB is changed from [1,2] to
> [3,4].
>
> 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
More information about the Python-list
mailing list