0

When writing a basic program today needed for fibonacci numbers, I came across the following situation to initialize two variables x & y at the same time.

I had originally written

x=1
y=2
......
x = y
y = x+y

Which obviously doesnt work to initialize both at the same time because because x becomes 2 leading to y becoming 4, which doesn't follow the the fibonacci sequence.

It had to be replaced with the following (that I didn't know was possible before searching):

x,y = y,x+y

And thus this produces the right sequence (x=2 and y =3)

My question is why this works? Or more specifically, what is happening with the memory allocation of variables underlying the syntax of that line of code. Are we telling the compiler to change y=x+y using x's previous value before its changed to y's previous value?

Thanks for all the help :)

Hushus46
  • 121
  • 2

2 Answers2

2

In assignment statements (x=y and friends), Python will always fully evaluate the right side of the statement before assigning. In this case, comma-delimited things automagically evaluate into tuples (y, x+y) or (2, 3). Then it gets to try to assign them- and it sees there are two things to assign and two values from the tuple to unpack, at which point it assigns them in order properly (first->first, second->second)

Delioth
  • 1,564
  • 10
  • 16
1

This assignment occurs in parts.

  1. A tuple is created from y, x+y.
  2. The tuple is broken back down into two parts again to be assigned to x and y through tuple unpacking.

The x+y will be calculated before the tuple is created, which occurs before the assignment, so it uses the original values.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622