How can this be?

Robin Munn rmunn at pobox.com
Fri Feb 6 13:10:57 EST 2004


r.e.s. <r.s at ZZmindspring.com> wrote:
> "Paul Prescod" <paul at prescod.net> wrote ...
>
>> You sent a reference to L into the function. The function probably 
>> mutated it. If you wish the function to work with a copy, try this:
>> 
>>       from A import *
>>       L = [0]
>>       print L
>>       x = f(L[:], 'a data string')
>>       print L
>> 
>> This is normal and often useful behaviour.
>
> I can see that it would be -- Thanks for answering 
> a beginner's question. I notice also the following:
>
>     def f(L): 
>         L[0] = 1
>     
>     def g(L):
>         L = [1]
>
>     L1 = [0],  L2 = [0]
>
>     f(L1), g(L2)
>
> ... L1 gets mutated, but not L2 (even though both
> references were passed).  It's probably explained 
> in the tutorial -- which I'm now going to re-read.

Fredrik Lundh's short article on Python objects (which starts with the
helpful advice "Reset your brain") is also useful as a starting point:

    http://effbot.org/zone/python-objects.htm

-- 
Robin Munn
rmunn at pobox.com



More information about the Python-list mailing list