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

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

    Does not work for multidimensional arrays, because references are used here.

    import numpy as np
    
    # swaps
    data = np.random.random(2)
    print(data)
    data[0], data[1] = data[1], data[0]
    print(data)
    
    # does not swap
    data = np.random.random((2, 2))
    print(data)
    data[0], data[1] = data[1], data[0]
    print(data)
    

    See also Swap slices of Numpy arrays

提交回复
热议问题