Scope troubles with a swap function

Matthew D. Wood woodm at
Fri Aug 10 21:40:34 CEST 2001

Hans Nowak wrote:

>> ===== Original Message From "Matthew D. Wood" <woodm at> =====
>> Ok, I've been banging my head against this for a sufficiently long time
>> that I feel justified in presenting this personal challenge to the list.
>> How do you make a swap function?
> You don't need to. :)  Use:
>   a, b = b, a

That makes me so mad that I didn't think of that.  Great suggestion.  (I 
feel really dumb...)

>> How do you make a function or a callable object instance that will do
>> what the following code intends to do:
>>   def swap (heaven, hell) :
>>           purgatory = heaven
>>           heaven = hell
>>           hell = purgatory
> Python's internal workings are very different from languages like C and 
> Pascal. A Python "variable" is not a location in memory that you can fill with 
> arbitrary data. This Pascal code:
>   X := 3;
>   X := 42;
> changes the value of X, which resides at a certain location in memory. But the 
> equivalent Python code
>   x = 3
>   x = 42
> does not do exactly the same; rather, it binds the name 'x' to the value 3, 
> then rebinds that name to the value 42. Other people explain this better than 
> me; see
> HTH,
> --Hans Nowak
Yeah, from what I have found, the best way to think about things is that 
everything is a reference.  However, you can't affect the value of a 
passed parameter.  You can however, effect the contents of that 
reference.  (You can't point to a different list, but you can screw with 
the contents of the current list.)  I just couldn't figure out how to 
get around that problem.

But thanks to you, I can.  I love this list!

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Python-list mailing list