-1

I had a question on how python code can be formatted.

 (q, a), b = divmod(b, a), a
        y0, y1 = y1, y0 - q * y1

For something like above, how do the commas to demonstrate variables work? Can someone show how this code would look without the use of commas between y0 and y1, or the (q,a)? I know it must be some sort of way to optimize the code.

JDog1999
  • 15
  • 1

1 Answers1

1

Commas at assigments are used for tuple creation on the right side and unpacking on the left side, e.g:

x, y = 1, 3

Which is functionally equivalent to

x = 1
y = 3

Or for example list unpacking, e.g:

example_list = [1, 4, 5]
x, y, z = example_list

Which is functionally equivalent to:

x = example_list[0]
y = example_list[1]
z = example_list[2]

So your code without "commas" would be:

(q, a) = divmod(b, a) # unpacking
b = a
old_y0 = y0
y0 = y1
y1 = old_y0 - q * y1

The reason for this is mostly convenience and not optimization of the code.

Yannick Funk
  • 1,319
  • 10
  • 23
  • 2
    your last example is wrong because you update `y0 = y1` and later `y1 = y0 - q * y1` uses new value in `y0` but it has to use old value. You have to keep `old_y0 = y0` and late `y1 = old_y0 - q * y1` – furas Sep 09 '20 at 14:31
  • 2
    "chained assignment" is the wrong term. On the right side of the equal sign you create a tuple and on the left side it's called "tuple unpacking". – Matthias Sep 09 '20 at 14:39
  • 1
    The final code is not exactly equivalent, as looking at the byte code using `dis.dis` would show, though it is functionally equivalent. – John Coleman Sep 09 '20 at 14:42