Multiple assignment and evaluation order in Python

前端 未结 10 2115
醉酒成梦
醉酒成梦 2020-11-22 01:41

What is the difference between the following Python expressions:

# First:

x,y = y,x+y

# Second:

x = y
y = x+y

First gives diffe

10条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-22 02:17

    In the second case, you assign x+y to x

    In the first case, the second result (x+y) is assigned to y

    This is why you obtain different results.

    After your edit

    This happen because, in the statement

    x,y = y,x+y
    

    all variables at the right member are evaluated and, then, are stored in the left members. So first proceed with right member, and second with the left member.

    In the second statement

    x = y
    y = x + y
    

    yo first evaluated y and assign it to x; in that way, the sum of x+y is equivalent to a sum of y+y and not of x+x wich is the first case.

提交回复
热议问题