Easy questions from a python beginner

Duncan Booth duncan.booth at invalid.invalid
Fri Jul 23 05:26:02 EDT 2010


Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> wrote:

> On Thu, 22 Jul 2010 22:47:11 -0400, wheres pythonmonks wrote:
> 
>> Thanks for pointing out that swap (and my swap2) don't work everywhere
>> -- is there a way to get it to work inside functions?

Consider languages where you can easily write a swap function (or any other 
function that updates its arguments). e.g. consider C or C#.

For C your function must take pointers to the variables, so when you call 
swap you have to make this explicit by taking the address of each variable:

   foo(&x, &y);

For C# the function takes references to the variables. Again you have to 
also make this explicit at the point of call by prefixing the argument with 
'ref':

   foo(ref x, ref y);

Python is really no different: if you want a function to rebind its 
arguments you have to make that explicit at the point of call. The only 
difference is that in Python you make the rebinding explicit by assigning 
to the names:

  x, y = foo(x, y)


-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list