简体   繁体   中英

execution order for swap function

My naive understanding is that we need a temporary variable to perform a swapping operation. Can someone tell me how the code below can help swap without the use of any temporary variables?

def swap(i,j,array): 
    array[i], array[j] = array[j],array[i]

Note: You can find this used extensively in sorting algorithms

Both sides are treated as tuples, in python (and many other functional languages) you can pack and unpack them freely.

The RHS gets packed into a new tuple, the the LHS unpacks it again, but the opposite way around.

There's more on tuples and unpacking here: https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM