Question about Pass-by-object-reference?

emile emile at fenx.com
Tue Jul 22 22:46:25 CEST 2014


On 07/22/2014 01:35 PM, Peter Pearson wrote:
> On Tue, 22 Jul 2014 12:34:51 -0700 (PDT), fl <rxjwg98 at gmail.com> wrote:
> [snip]
>>
>> But I don't understand the reassign function result:
>>
>>>>> def reassign(list):
>> ... 	list=[0,1]
>> ...
>>>>> list=[0]
>>>>> reassign(list)
>>>>> print list
>> [0]
>
> When you say "def reassign(list)", that means "I'm defining a function
> to which the caller will pass one object, and within this function I'm
> going to refer to that object by the name 'list'."
>
> Then, when you say "list=[0,1]", that means "Create the object [0,1],
> and assign to it the name 'list'."  At this point, there is no longer
> any name that refers to the object that the caller passed.
>
> You might have thought that "list=[0,1]" would modify the caller-passed
> object, but that's not what happens.  That's not what "=" means.
>

However, if that is the behavior you were after, you can get there.


def reassign(mylist):  # no reason to shadow the list builtin
     mylist[:] = [0,1]

mylist = [1]
reassign(mylist)
mylist


Emile





More information about the Python-list mailing list