A question on modification of a list via a function invocation

Antoon Pardon antoon.pardon at vub.be
Thu Sep 7 03:57:57 EDT 2017


Op 07-09-17 om 03:27 schreef Steve D'Aprano:
>
>> Yes it is. Pascal VAR parameters are exactly like Python a assignment.
> Proof by assertion?
>
> "It is true, because I say it is true!"

I didn't just assert, I also explained. That you choose to
ignore the explanation doesn't make it a proof by assertion.

Calling a function/procedure with a VAR parameter in Pascal,
makes the parameter an alias of the argument. Just like
a python assignment makes an alias.

This can be shown by the fact that if one mutates the enity
through one alias, the effect can be seen through the other
alias.

Now the counter argument is that if you assign to the parameter
in the function, this change doesn't effect the argument with
which the function was called in Python. But this ignores the
fact that the assignment in python doesn't mutate the entity
it refers to or is bound to or whatever you want to call it.
Instead it makes the parameter now refer/bound to something else.

Expecting that one should be able to write a swap function
should the parameters in python be like VAR parameters in
Pascal is ignoring how assignment semantics in python differ
from the assignment semantics in Pascal.

This can be shown by writing a swap function for lists because
we can simulate a mutating assignment with lists.

def swap(lp1, lp2):
	tmp = list(lp1)
	lp1[:] = lp2
	lp2[:] = tmp

ls1 = [1, 3, 5, 7]
ls2 = [0, 2, 4, 6]

print(id(ls1), ls1)
print(id(ls2), ls2)
print("========")

swap(ls1, ls2)
print(id(ls1), ls1)
print(id(ls2), ls2)

Which on my computer produces:

140178186781768 [1, 3, 5, 7]
140178186794632 [0, 2, 4, 6]
========
140178186781768 [0, 2, 4, 6]
140178186794632 [1, 3, 5, 7]


-- 
Antoon Pardon.





More information about the Python-list mailing list