Is there a standardized method to swap two variables in Python?

后端 未结 7 978
天涯浪人
天涯浪人 2020-11-22 00:09

In Python, I\'ve seen two variable values swapped using this syntax:

left, right = right, left

Is this considered the standard way to swap

7条回答
  •  忘掉有多难
    2020-11-22 00:15

    I know three ways to swap variables, but a, b = b, a is the simplest. There is

    XOR (for integers)

    x = x ^ y
    y = y ^ x
    x = x ^ y
    

    Or concisely,

    x ^= y
    y ^= x
    x ^= y
    

    Temporary variable

    w = x
    x = y
    y = w
    del w
    

    Tuple swap

    x, y = y, x
    

提交回复
热议问题