Swap Items in an Array
Swap Two Variables
In Python, swapping two variables is a oneliner: a, b = b, a
.
In languages such as Java, swapping requires the use of a temporary variable:


If we know the two variables are integers, can we swap them without using a temporary variable?


It’s a fun little exercise to convince yourself that the above procedure indeed works. Keep in mind that the XOR operator is commutative and that x ^ x = 1
.
Another way is to use the plus and minus operators:


Note that the above two procedures only work when a
and b
are integers.
Swap Two Items in an Array
Given a list L
and two indices i
and j
, we can swap the L[i]
and L[j]
in oneline: L[i], L[j] = L[j], L[i]
.
Shuffle an Array
Given an array, write a program to generate a random permutation of array elements.
The Fisher–Yates shuffle is a wellknown algorithm to solve this problem. In pseudocode, the algorithm works as follows
for i from n−1 down to 1 do
j ← random integer such that 0 ≤ j ≤ i
swap a[j] and a[i]
Here’s the Python implementation:


Note that random.randint(a, b)
returns a random integer n
such that a <= n <= b
.
Let’s see the function in action:

