a wierd parameter passing behavior
Peter Abel
p-abel at t-online.de
Wed Jun 4 13:28:12 EDT 2003
mpradella at yahoo.it (Torvo Sollazzo) wrote in message news:<5ca99eab.0306040529.2d6f85 at posting.google.com>...
> Hi!
>
> 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
>
> def f() :
> l = [1]
> p(l)
> print l
> l = [1]
> p1(l)
> print l
>
> If I call f(), I obtain the following results:
> [2,3]
> [1]
> Why p1() is different from p()? The list l should be passed by
> reference in both cases, while it seems that "l = l + [3]" creates a
> new local variable, also called l.
>
> Any idea?
> Many thanks,
> TS
Though others already gave the explanation, here
the same one from another point of view:
>>> l=[1]
>>> id(l)
14076416
>>> #l was bound to the object [1]
>>> l+=[1]
>>> id(l)
14076416
>>> #l remains bound to the same object, which was extended
>>> l.extend([1])
>>> #l remains bound to the same object, which was extended
>>> id(l)
14076416
>>> l.append(1)
>>> #l remains bound to the same object, which was extended
>>> id(l)
14076416
>>> l
[1, 1, 1, 1]
>>> l=l+[1]
>>> #l is bound to a new object, which consists of the information
>>> # (**NOT THE REFERENCE**) of the old one, plus an extension
>>> id(l)
14150320
>>> l
[1, 1, 1, 1, 1]
>>>
Regards
Peter
More information about the Python-list
mailing list