+ 1
what is the difference
a, b = b, a Is it equal to the : a = b b = a ?
4 RĂ©ponses
+ 2
Well, Lets understand it with the help of an example:
Case 1-
# a,b = b,a
# means essentially the following:
a=2
b=5
temp=a
a=b
b= temp
print('a:', a)
print('b:',b)
>>> a: 5
>>> b: 2
Case 2-
# What you wrote second
a=2
b=5
a=b
b=a
print('a:', a)
print('b:',b)
>>> a: 5
>>> b: 5
+ 1
a, b = b, a means you are switching the values of a and b.
a = 2
b = 5
a, b = b, a
print(a) # 5
print(b) # 2
a = b or b = a means you will set them to be the same.
+ 1
It is, if understood as done *simultaneously*.
If in iterative way, it is rather equivalent to:
a = a + b
b = a - b
a = a - b