Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python multiple variable assignment confusion

Tags:

python

My first day in Python and get confused with a very short example. Hope anyone can provide some explanation about why there is some difference between these several versions. Please!

V1: the output is 1, 1, 2, 3, 5, 8

a, b = 0, 1
while b < 10:
    print(b)
    a, b = b, a+b

V2: the output is 1, 2, 4, 8

a, b = 0, 1
while b < 10:
    print(b)
    a = b
    b = a+b
like image 607
CY_ Avatar asked Nov 04 '16 14:11

CY_


People also ask

Does Python support multiple assignment to multiple variables?

Multiple assignment in Python: Assign multiple values or the same value to multiple variables. In Python, use the = operator to assign values to variables. You can assign values to multiple variables on one line.

Can you assign multiple variables at once Python?

Assign Values to Multiple Variables in One Line Given above is the mechanism for assigning just variables in Python but it is possible to assign multiple variables at the same time. Python assigns values from right to left.

Can you assign multiple variables at once?

Multiple variable assignment is also known as tuple unpacking or iterable unpacking. It allows us to assign multiple variables at the same time in one single line of code. In the example above, we assigned three string values to three variables in one shot. As the output shows, the assignment works as we expect.


1 Answers

In the first version, the right hand is evaluated first, so b hasn't been incremented when you add it.

To step through the first version for a couple iterations:

1.

a = 0
b = 1
a, b = 1, 1  # b is 1, and a is 0

2.

a = 1
b = 1
a, b = 1, 2  # b is 1 and a is 1

3.

a = 1
b = 2
a, b = 2, 3  # b is 2 and a is 1

In the second version, b is assigned before you add it, so here's how the second version goes:

1.

a = 0
b = 1
a = b  # a is now 1.
b = a + b  # b is now 2, because both a and b are 1.

2.

a = 1
b = 2
a = b  # a is now 2.
b = a + b  # b is now 4, because both a and b are 2.
like image 132
Morgan Thrapp Avatar answered Sep 18 '22 00:09

Morgan Thrapp