What does this expression do: (x, y) = (y, x % y)?

Viewed 159

I see below code but do not know what does it do.

(x, y) = (y, x % y)

At the beginning I thought it does below:

x=y
y=x%y

But I noticed I am not right. Can someone explain what (x, y) = (y, x % y) does?

4 Answers

It's called tuple assignment/unpacking, and to reproduce it linearly, you need a temporary location to store the value of x.

It is more equivalent to:

temp=x
x=y
y=temp%y

You're right, it does what you think it does. x is assigned the value of y and y is assigned the value of x%y

Example:

>>> x=5
>>> y=10
>>> (x, y) = (y, x % y)
>>> x
10
>>> y
5
>>> 

x becomes 10 (i.e., the value of y) and y becomes x%y= 5%10 =5

It does this:

t1 = y
t2 = x % y
x = t1
y = t2
del t1, t2

except that the variables t1 and t2 never actually exist. In other words, it computes the new values to assign to both x and y based on their old values, and changes both at once.

I don't have the exact terminology here.

(x, y) = (y, x % y) is doing x=y, y=x%y and the same time. If you are running this two lines in sequence, you are pass the value of y to x the do the divide.

Related