-1

Is this syntax:

x, y = 0,1

while y < 50:
    print(y)
    x, y = y, x+y

The same as this:

x = 0
y = 1

while y < 50:
    print(y)
    x = y
    y = x+y

If so why do they print different results? I'm trying to understand how the first code prints: 1, 1, 3, 5, 8, 13, 21, 34 because when I debug in my head and run the second code it prints: 1, 2, 8, 16, 32. Basically I cannot understand how the first code is working line by line.

Georgy
  • 12,464
  • 7
  • 65
  • 73
JeromeCode
  • 117
  • 9
  • In the second, first you reassign `x` with the value of `y` and then assign `y` with `x + y`. In Python, the right hand of an operation is evaluated first. So `x, y = y, x + y` is first evaluated on the right side and then the assignments occur. – accdias Jan 20 '20 at 18:22
  • I guess this illustrates it better `x, y = 0, 1`, leads to `x = 0`, `y = 1`. Then `x, y = y, x + y` leads to `x, y = 1, 0 + 1`, that results in `x = 1` and `y = 1`. – accdias Jan 20 '20 at 18:27
  • 5
    Does this answer your question? [Multiple assignment and evaluation order in Python](https://stackoverflow.com/questions/8725673/multiple-assignment-and-evaluation-order-in-python) – maverick6912 Jan 20 '20 at 18:27

3 Answers3

0

They aren't the same.

In multiple assignments such as x, y = y, x+y, the right side is evaluated first. So x+y is evaluated, then y is set equal to x+y.

Say x=0 and y=1. Then, x, y = y, x+y evaluates to x, y = 1, 0+1, so x, y = 1, 1. y = 1.

In the second example, x = y causes x = 1, and the next line y = x+y causes y = 2.

jimsu2012
  • 170
  • 3
0

The reason they give different results is that in the first one, you modify x and y at the same time, however in the second code, first you increase x and then you modify y, which is unfavorable.

0

The first code uses multiple assignment in Python, where you create a tuple and loop over it and assign values to each variable

This is how Python handles your line :

(x,y) = (y,x+y)

This code is correct : you can traverse and observe it,

x,y = 0,1
x,y = 1,1
x,y = 1,2
x,y = 2,3
x,y = 3,5

The second code is totally wrong :

x = y
y = x+y

Since x is initialized with y in the first line : the second line is consequently y = 2*y, hence your output keeps on doubling

Suraj
  • 2,253
  • 3
  • 17
  • 48