Tuple matching vs. variable assignment in Python

Sorath :

I always thought that tuple matching was the same as variable assignment, so I thought these two pieces of code did the same thing:

a = b
b = a + b

and

a, b = b, a + b

However, that has not been the case in the following two pieces of code that give me different outputs:

def fib(seq_len):
    a = 1
    b = 1
    sequence = []
    for i in range(seq_len):
        sequence.append(a)
        a, b = b, a + b
    return sequence

fib(10)

which gives the output:

[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

and

def fib(seq_len):
    a = 1
    b = 1
    sequence = []
    for i in range(seq_len):
        sequence.append(a)
        a = b
        b = a + b
    return sequence

fib(10)

which gives the following output:

[1, 1, 2, 4, 8, 16, 32, 64, 128, 256]

It seems that in the first definition of fib, the previous value of a is being used for a, b = b, a + b but I don't understand how it remembers that previous value because we have assigned a to another value i.e. b before moving on to b = a + b

chepner :

a, b = b, a + b is equivalent to

t = b, a + b
a, b = t

not

a = b
b = a + b  # essentially, b = 2 * b

The right-hand side must be fully evaluated before you perform either assignment.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=19441&siteId=1