0

Why does this:

def make_fib():
    cur, next = 0, 1
    def fib():
        nonlocal cur, next
        result = cur
        cur, next = next, cur + next
        return result
    return fib

Work differently than:

def make_fib():
    cur, next = 0, 1
    def fib():
        nonlocal cur, next
        result = cur
        cur = next
        next = cur + next
        return result
    return fib

I see how the second one messes up because at cur = next and next = cur + next because essentially it will become next = next + next but why does the first one run differently?

4
  • How about next = result + next Commented Oct 27, 2019 at 6:55
  • @cricket_007 Yes that would work but how does the first one differ from the bottom one though. Shouldn't cur, next = next, cur + next essentially be the bottom one? Commented Oct 27, 2019 at 6:56
  • 1
    the right-hand side is evaluated first, then applied. So essentially, both assignments happen "at the same time" Commented Oct 27, 2019 at 6:58
  • @njzk2 Ok so they happen at the same time. What do you mean by the right hand side is evaluated first. Can you use my example? Commented Oct 27, 2019 at 7:00

1 Answer 1

6
cur, next = next, cur + next

is the same operation as:

# right-hand side operations
tmp_1 = next
tmp_2 = cur + next

# assignment
cur = tmp_1
next = tmp_2

Because the right-hand side is fully evaluated, and then the values are assigned to the left-hand side

Sign up to request clarification or add additional context in comments.

2 Comments

ty for your explanation
Here is the documentation reference for that: "An assignment statement evaluates the expression list (… this can be … a comma-separated list, … yielding a tuple)." There is also a caveat for cases like i, x[i] = 1, 2.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.