GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

How just x,y = y,x swaps value in python, is it parallel or something, please explain ?

asked Mar 6, 2016 by no3

1 Answer

Actually whenever you write comma separated value python implicitly makes a tuple out of them so when you write (x, y)  it actually makes a tuple t on which operation are done.

so your code  x, y = y, x internally breaks into,

x = 5
y = 6
temp = (x, y)  # evaluates to (5, 6)
y, x = temp

so you can think of these two operations take place separately. First the tuple is formed and evaluated, then the tuple is unpacked back into the variables. The net effect is that the values of your two variables are interchanged.

But remember python does optimization on such statement so always tuple formation and unpacking won't happen but intention is same.

answered Mar 6, 2016 by utkarsh111
...