Search code examples
pythonpython-3.xiterable-unpacking

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


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?


Solution

  • 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