2.5.ASSIGNMENTSTATEMENTS 19
2.5.3 SimultaneousAssignment
Thereis analternative formoftheassignmentstatementthatallowsustocalculateseveralvaluesallatthe
sametime.It lookslike this:
, , ..., =
Thisiscalledsimultaneousassignment. Semantically, thistellsPythontoevaluatealltheexpressionson
theright-handsideandthenassignthesevaluestothecorrespondingvariablesnamedontheleft-handside.
Here’s anexample.
sum, diff = x+y, x-y
Heresumwouldgetthesumofxandyanddiffwouldgetthedifference.
Thisformofassignmentseemsstrangeatfirst,butit canprove remarkablyuseful.Here’s anexample.
Supposeyouhave two variablesxandyandyouwanttoswapthevalues. Thatis,youwantthevalue
currentlystoredinxtobeinyandthevaluethatis currentlyinytobestoredinx. Atfirst,youmightthink
thiscouldbedonewithtwo simpleassignments.
x = y
y = x
Thisdoesn’t work.We cantracetheexecutionofthesestatementsstep-by-steptoseewhy.
Supposexandystartwiththevalues2 and4. Let’s examinethelogicoftheprogramtoseehowthe
variableschange.Thefollowingsequenceusescommentstodescribewhathappenstothevariablesasthese
two statementsareexecuted.
variables x y
initial values 2 4
x = y
now 4 4
y = x
final 4 4
Seehow thefirststatementclobberstheoriginalvalueofxbyassigningtoit thevalueofy? Whenwethen
assignxtoyinthesecondstep,wejustendupwithtwo copiesoftheoriginalyvalue.
Onewaytomake theswapworkis tointroduceanadditionalvariablethattemporarilyremembersthe
originalvalueofx.
temp = x
x = y
y = temp
Let’s walk-throughthissequencetoseehow it works.
variables x y temp
initial values 2 4 no valueyet
temp = x
2 4 2
x = y
4 4 2
y = temp
4 2 2
Asyoucanseefromthefinalvaluesofxandy, theswapwassuccessfulinthiscase.
Thissortofthree-wayshuffleis commoninotherprogramminglanguages.InPython,thesimultaneous
assignmentstatementoffersanelegantalternative. Hereis a simplerPythonequivalent:
x, y = y, x