a wierd parameter passing behavior

POYEN OP Olivier (DCL) Olivier.POYEN at clf-dexia.com
Wed Jun 4 15:59:49 CEST 2003



> -----Message d'origine-----
> De : Torvo Sollazzo [mailto:mpradella at yahoo.it]
> Envoyé : mercredi 4 juin 2003 15:30
> À : python-list at python.org
> Objet : a wierd parameter passing behavior
> 
> 
> Hi!
> 
> I found a strange parameter passing behavior in Python (v. 2.2.2).
> Look at this piece of code:


One mutates l in place, while the other affect a new local variable : 



> def p(l) :
>     l += [3]
>     l[0] = 2
> 

Here, you change a mutable object in place (ensured byt the += stuff) 


> def p1(l) :
>     l = l + [3]
>     l[0] = 2
> 


Here you create a local variable l, assigning the value l+[3] to it. Then you change this local variable first element.
But outside the scope of the p1 function, this "new" l does not exists, ence l is still [1]

On the contrary, since list are mutable objects in python, if you change list *in place* with l.__iadd__(stuff) (or l += stuff), it change l without creating a new one, a local one.


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

> 
-------------- next part --------------
-----------------------------------------------------------------

Ce message est confidentiel ; son contenu ne represente en aucun

cas un engagement de la part de Dexia Credit Local ou de Dexia

CLF Banque. Toute publication, utilisation ou diffusion, meme

partielle, doit etre autorisee prealablement par l'emetteur. Si

vous n'etes pas destinataire de ce message, merci d'en avertir

immediatement l'expediteur.



This message is confidential ; its contents do not constitute a

commitment by Dexia Credit Local or Dexia CLF Banque. Any

unauthorised disclosure, use or dissemination, either whole or

partial, is prohibited. If you are not the intended recipient of

the message, please notify the sender immediately.

-----------------------------------------------------------------

Consultez notre site internet www.dexia-clf.fr

La cle d'une gestion optimisee du secteur public local

-----------------------------------------------------------------


More information about the Python-list mailing list