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

后端 未结 7 960
天涯浪人
天涯浪人 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:16

    To get around the problems explained by eyquem, you could use the copy module to return a tuple containing (reversed) copies of the values, via a function:

    from copy import copy
    
    def swapper(x, y):
      return (copy(y), copy(x))
    

    Same function as a lambda:

    swapper = lambda x, y: (copy(y), copy(x))
    

    Then, assign those to the desired names, like this:

    x, y = swapper(y, x)
    

    NOTE: if you wanted to you could import/use deepcopy instead of copy.

提交回复
热议问题