Why Doesn’t Executing "a, X = X, A" Twice Result In A Change Of Values?
While watching a video explaining about a quiz I found this code snippet: a, x = x, a a, x = x, a print a print x The video says that the end result is x and a swap, and if we do
Solution 1:
The syntax a,x = x,a
swaps the values because the assignments to the right hand side of the assignment operator (=
) are first evaluated and then assigned to their values, as explained here. It logically follows that if this operation is performed twice, then the second swap returns the variables to their original values.
Note that if instead you wrote a = x; x = a
then a
and x
would both end up as the start value of x
because each statement is evaluated sequentially from left to right.
Demonstration:
>>>a = 1>>>x = 2>>>a,x = x,a>>>a,x
(2, 1)
>>>>>>a = 1>>>x = 2>>>a = x; x = a>>>a,x
(2, 2)
Post a Comment for "Why Doesn’t Executing "a, X = X, A" Twice Result In A Change Of Values?"