Yes It isn't exactly the same , because when you write -
a, b = b, a+b
The value of a
and b
at the time of executing the statement is considered, lets say before this statement, a=1
, b=2
, then first right hand side is calculated , so b=2
is calculated and a+b=3
is calculated. Then the assignment occurs, that is a
is assigned value 2
and b
is assigned value 3
.
But when you write -
a = b
b = a+b
The assignment occurs along with calculation, that is first b=2
is calculated, then assigned to a , so a becomes 2 , then a+b is calculated (with the changed value of a) , so a+b=4
and it is assigned to b , so b
becomes 4
, and hence the difference.
a,b = b, a
This is a shorthand for swapping values of a
and b
, please note that if you want to swap the values without using this notation, you would need a temporary variable.
Internally how it works is that the right hand sid is made into a tuple, and then the values are unpacked, a simple test to see this is -
>>> a = 5
>>> b = 10
>>> t = a, b
>>> t
(5, 10)
>>> b, a = t