Multiple assignment and evaluation order in Python

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

    The first expression:

    1. Creates a temporary tuple with value y,x+y
    2. Assigned in to another temporary tuple
    3. Extract the tuple to variables x and y

    The second statement is actually two expressions, without the tuple usage.

    The surprise is, the first expression is actually:

    temp=x
    x=y
    y=temp+y
    

    You can learn more about the usage of comma in "Parenthesized forms".

提交回复
热议问题