Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Are a,b=1,2 and a=1;b=2 strictly equivalent?

I am puzzled with the following:

This works:

a, b = 1071, 1029
while(a%b != 0):
    a, b = b, a%b

But, the following snippet returns a ZeroDivisionError error message:

a, b = 1071, 1029
while(a%b != 0):
    a = b; b = a%b

while I expected both would be strictly equivalent.

Can anyone throw the light on this, please?

like image 329
tagoma Avatar asked May 30 '26 01:05

tagoma


1 Answers

No. In

a, b = b, a%b

the right-hand side is evaluated into a tuple first, so a%b is calculated using the original value of a. In contrast,

a = b; b = a%b

a%b is calculated after a as been assigned the value of b, assigning a different result to b.

like image 108
chepner Avatar answered Jun 01 '26 14:06

chepner