Can Python function return multiple data?

Steven D'Aprano steve at pearwood.info
Thu Jun 4 18:31:41 EDT 2015


On Fri, 5 Jun 2015 03:30 am, random832 at fastmail.us wrote:

> On Thu, Jun 4, 2015, at 13:11, Steven D'Aprano wrote:
>> You need at least one more test to prove pass by value: you need to
>> demonstrate that the value bound to y is copied when passed to the
>> function. E.g. pass a mutable value (say, a list) and mutate it inside
>> the
>> function. If the list in the outer scope is *not* mutated, then and only
>> then can you say it is pass by value.
> 
> That's not true at all. Being able to mutate the object doesn't make it
> not-pass-by-value any more than being able to use an int argument as an 
> index to mutate a global array makes the int not-pass-by-value.
> 
> a = [0]*16
> 
> def f(x, i):
>     x[i] = 3
> 
> f(a, 0)
> 
> If x is not pass-by-value, then clearly i is also not pass-by-value,
> despite integers being immutable. 

Neither are pass by value, and the results of running that code are
consistent with that fact. Nothing in the above code snippet shows pass by
value behaviour: neither the list a nor the literal 0 is copied. We know
that the list is not copied because the mutation operation inside the
function shows up on the outside (it affects the list bound to a). Nothing
in your code demonstrates that 0 is not copied, but this code snippet does:

x = 0  # or use any value you like
print(id(x))

def test(arg):
    print(id(arg))


test(x)



> Being able to use an argument to cause 
> a side effect does not mean the argument has not been passed by value.

Of course it does. The lack of side-effects is the defining characteristic
of pass by value: since the argument is copied, any direct mutations you
apply to it cannot affect the original.


> a hasn't changed,

Yes it has. It was [0,0,0,...0] and now it is [3,0,0,...0]. That's a
mutation to the value, and it is visible in the outer scope. Hence, a has
not been copied, which means it wasn't passed by value.


> 0 hasn't changed, the only thing that has changed is 
> the list object, which is *not the same thing as a*.

This is an interesting (and sometimes useful) distinction you are making,
between the value of a variable and the variable itself, but it is not
relevant to the discussion of pass by value.



-- 
Steven




More information about the Python-list mailing list