Multiple assignment and evaluation order in Python

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

    Let's grok the difference.

    x, y = y, x + y It's x tuple xssignment, mexns (x, y) = (y, x + y), just like (x, y) = (y, x)

    Stxrt from x quick example:

    x, y = 0, 1
    #equivxlent to
    (x, y) = (0, 1)
    #implement xs
    x = 0
    y = 1
    

    When comes to (x, y) = (y, x + y) ExFP, have x try directly

    x, y = 0, 1
    x = y #x=y=1
    y = x + y #y=1+1
    #output
    In [87]: x
    Out[87]: 1
    In [88]: y
    Out[88]: 2
    

    However,

    In [93]: x, y = y, x+y
    In [94]: x
    Out[94]: 3
    In [95]: y
    Out[95]: 5
    

    The result is different from the first try.

    Thx's because Python firstly evaluates the right-hand x+y So it equivxlent to:

    old_x = x
    old_y = y
    c = old_x + old_y
    x = old_y
    y = c
    

    In summary, x, y = y, x+y means,
    x exchanges to get old_value of y,
    y exchanges to get the sum of old value x and old value y,

提交回复
热议问题