0

What is the difference between this:

a, b = b, a+b

And this:

a = b
b = a+b

I'm trying to follow along in the examples in the documentation and the first form (multiple assignment syntax) seems complicated to me. I tried to simplify it with the second example but it's not giving the same results. I'm clearly interpreting the first statement wrong. What am I missing?

Micah
  • 111,873
  • 86
  • 233
  • 325

1 Answers1

5

Multiple assignment evaluates the values of everything on the right hand side before changing any of the values of the left hand side.

In other words, the difference is this:

a = 1
b = 2
a = b                  # a = 2
b = a + b              # b = 2 + 2

vs. this:

a = 1
b = 2
a, b = b, a + b        # a, b = 2, 1 + 2

Another way of thinking about it is that it's the equivalent of constructing a tuple and then deconstructing it again (which is actually exactly what's going on, except without an explicit intermediate tuple):

a = 1
b = 2
_tuple = (b, a+b)
a = _tuple[0]
b = _tuple[1]
Amber
  • 507,862
  • 82
  • 626
  • 550