Easy questions from a python beginner

Steven D'Aprano steve-REMOVE-THIS at cybersource.com.au
Mon Jul 12 02:09:49 EDT 2010


On Sun, 11 Jul 2010 21:52:17 -0700, sturlamolden wrote:

> On 11 Jul, 21:37, "Alf P. Steinbach /Usenet" <alf.p.steinbach
> +use... at gmail.com> wrote:
> 
>> Oh, I wouldn't give that advice. It's meaningless mumbo-jumbo. Python
>> works like Java in this respect, that's all; neither Java nor Python
>> support 'swap'.
> 
> x,y = y,x


Of course that's a good alternative, but that's not what Alf, or the 
original poster, are talking about.

They're specifically talking about writing a function which swaps two 
variables in the enclosing scope. This is a good test of languages that 
support call-by-reference, e.g. Pascal:


procedure swap(var x:integer, var y: integer):
  VAR
    tmp: integer;
  BEGIN
    tmp := x;
    x := y;
    y := x;
  END;


If you pass two integer variables to swap(), Pascal will exchange their 
values. You can't do this in Python. You can get close if you assume the 
enclosing scope is global, or if you pass the name of the variables 
rather than the variables themselves, but even then you can't make it 
work reliably. Or at all.

Naturally the swap() function itself is not terribly useful in a language 
like Python that makes exchanging variables so easy, but there are other 
uses for call-by-reference that aren't quite so trivial. However, I can't 
think of anything off the top of my head, so here's another trivial 
example that can't work in Python:

s = "hello"
call_something_magic(s)
assert s == "goodbye"




-- 
Steven



More information about the Python-list mailing list