a wierd parameter passing behavior
Terry Reedy
tjreedy at udel.edu
Wed Jun 4 12:22:21 EDT 2003
"Torvo Sollazzo" <mpradella at yahoo.it> wrote in message
news:5ca99eab.0306040529.2d6f85 at posting.google.com...
> I found a strange parameter passing behavior in Python (v. 2.2.2).
> Look at this piece of code:
> def p(l) :
> l += [3]
> l[0] = 2
>
> def p1(l) :
> l = l + [3]
> l[0] = 2
...
> Why p1() is different from p()? The list l should be passed by
> reference in both cases,
We just had a long discussion on another thread about 'pass by value'
versus 'pass by reference' versus what Python does, which is to bind
local parameter names to actual arguments. I strongly recommend
sticking with the binding view.
> while it seems that "l = l + [3]" creates a new local variable, also
called l.
Better put: both functions have one local name (variable) 'l'. The
first mutates the object bound to l. The second leave the original
object alone and rebinds l to a new object. In this case, the new
object has a different value, but that is not essential. The new
object is not a new 'variable'.
Terry J. Reedy
More information about the Python-list
mailing list