[Tutor] Swapping variables ...

wesley chun wescpy at gmail.com
Mon Nov 12 07:42:40 CET 2007


On 11/10/07, O.R.Senthil Kumaran <orsenthil at gmail.com> wrote:
> >  After quizzing newbies in C on swapping without 3rd variable, I found this
> > to be really *cool* construct to swap :)
> > x = 10
> > y = 20
> > x,y = y,x
>
> Keep in mind that, this is actually a tuple assignment.
> A new tuple x,y is created with the older one y,x, and with the side effect thatthe variables are swapped as we see it.

you can dig even *deeper* within the tuple assignment.  keep in mind
that the right-hand side (RHS) is always evaluated 1st, whenever there
is an assignment operation.  an alias or reference mapping is made
using the variable name (in the current or designated namespace) to
whatever object appears on the RHS.

this means that 'x' on the LHS gets whatever object 'y' was
referencing during evaluation time, and likewise, 'y' becomes an alias
to whatever object 'x' was pointing to.  it's just a "coincidence"
that the new mapping variables are just reversed to what they were
previously. the interpreter makes no special distinction just because
this is the case.

if you are still thinking of variables as data structures which
contain values, you need to "unlearn what you have learned." :-)
variables in Python are merely references to objects and such
references can be manipulated at will. for example, a variable 'a' as
in 'a = 123' can be immediately reassigned to a string, i.e., "a =
'foo'". getting comfortable with objects, references, and the mapping
of names to objects are some ways of understanding Python more fully
and with greater success.

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


More information about the Tutor mailing list