Multiple assignment and evaluation order in Python

前端 未结 10 1917
醉酒成梦
醉酒成梦 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:11

    Other answers have already explained how it works, but I want to add a really concrete example.

    x = 1
    y = 2
    x, y = y, x+y
    

    In the last line, first the names are dereferenced like this:

    x, y = 2, 1+2
    

    Then the expression is evaluated:

    x, y = 2, 3
    

    Then the tuples are expanded and then the assignment happens, equivalent to:

    x = 2; y = 3
    

提交回复
热议问题