Multiple assignment and evaluation order in Python

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

    In an assignment statement, the right-hand side is always evaluated fully before doing the actual setting of variables. So,

    x, y = y, x + y
    

    evaluates y (let's call the result ham), evaluates x + y (call that spam), then sets x to ham and y to spam. I.e., it's like

    ham = y
    spam = x + y
    x = ham
    y = spam
    

    By contrast,

    x = y
    y = x + y
    

    sets x to y, then sets y to x (which == y) plus y, so it's equivalent to

    x = y
    y = y + y
    

提交回复
热议问题