2

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?

programandoconro
  • 2,378
  • 2
  • 18
  • 33
Nataliya
  • 79
  • 7

4 Answers4

7

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
smac89
  • 39,374
  • 15
  • 132
  • 179
4

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

a121
  • 798
  • 4
  • 9
  • 20
3

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.

zwol
  • 135,547
  • 38
  • 252
  • 361
3

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.

Moving Box
  • 95
  • 1
  • 4