gymguy42
gymguy42

Reputation: 37

Python Variable Assignment on One line

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?

Upvotes: 0

Views: 46

Answers (1)

njzk2
njzk2

Reputation: 39386

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

Upvotes: 6

Related Questions