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

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

    You can combine tuple and XOR swaps: x, y = x ^ x ^ y, x ^ y ^ y

    x, y = 10, 20
    
    print('Before swapping: x = %s, y = %s '%(x,y))
    
    x, y = x ^ x ^ y, x ^ y ^ y
    
    print('After swapping: x = %s, y = %s '%(x,y))
    

    or

    x, y = 10, 20
    
    print('Before swapping: x = %s, y = %s '%(x,y))
    
    print('After swapping: x = %s, y = %s '%(x ^ x ^ y, x ^ y ^ y))
    

    Using lambda:

    x, y = 10, 20
    
    print('Before swapping: x = %s, y = %s' % (x, y))
    
    swapper = lambda x, y : ((x ^ x ^ y), (x ^ y ^ y))
    
    print('After swapping: x = %s, y = %s ' % swapper(x, y))
    

    Output:

    Before swapping: x =  10 , y =  20
    After swapping: x =  20 , y =  10
    

提交回复
热议问题