The list is the most flexible container data type in Python, it represents an ordered collections of elements in which an element can be accessed by its index in the list.

Swapping elements is when two list items switch their positions in the list. This operation is especially common in in-place sorting algorithms where elements are compared and swapped depending on their relative order.

For example given a list ['apple', 'orange', 'mango', 'lemon'] if the first and the third elements are swapped the list elements will be ordered as   ['mango', 'orange', 'apple', 'lemon'].

We can achieve swap operation using various approaches as outlined below:

  • Using multiple assignment
  • Using an intermediate variable
  • Using pop() and insert() methods

Using multiple assignment

Python allows us to assign multiple comma separated values simultaneously e.g  a, b = b, a. We can use this feature combined with the list index assignment operation to swap two list elements.

#the list to swap
mylist = [0, 10, 20, 30, 40, 50]

#swap the first element with the last element
mylist[0], mylist[5] = mylist[5], mylist[0]

print(mylist)

In the above example, the line mylist[0], mylist[5] = mylist[5], mylist[0] makes index 0 of the list to hold the value currently held at index 5 of the list and simultaneously makes the  index 5 of the list to hold the value currently held at index 0. The resulting effect is a swap of the values at indexes 0 and 5.

We can fine tune the above program to swap values of at any index be defining a function which takes the list and the two indices as the arguments.

def swap(lst, i, j):
    '''swap the values at i and j positions of the list'''
    lst[i], lst[j] = lst[j], lst[i]

mylist = ['Python', 'Java', 'C++', 'PHP']

#swap the second and the third elements
swap(mylist, 2, 1)

print(mylist)

Using an intermediate variable 

To swap two elements in a list, we can:

  1. Define an intermediate variable to hold one of the two values
  2. Overwrite the position where the value was with the value at the other position
  3.  put the value from the temporary variable in the other position.
def swap(lst, i, j):
    #temporary variable
    temp = lst[i]

    #ovewrite postion i with the value of j
    lst[i] = lst[j]

    #put the temporary value at j
    lst[j] = temp

mylist = [100, 200, 300, 400, 500]

swap(mylist, 0, 2)

print(mylist)

Using pop() and insert() methods

This approach comes last because it is less efficient than the other two discussed above.  

The pop() method when called with an integer argument removes the element at the given index from the list and returns it.

pop(i)

Where i is the index  to be removed from the list.

lst = [10, 20, 30, 40, 50]

lst.pop(2)

print(lst)

The  insert() method, on the other hand, inserts an element at the specified position in the list.

insert(i, v)

Where i is the index in the list to insert element v

lst = [10, 20, 40, 50]

lst.insert(2, 30)

print(lst)

We can use the combined features of the two functions to swap two list elements.

mylist = [0, 100, 200, 300, 400, 500]

def swap(lst, i, j):
    if i == j:
         return

    i, j = min(i, j), max(i, j)

    temp1 = lst.pop(i)
    temp2 = lst.pop(j-1)

    lst.insert(i, temp2)
    lst.insert(j, temp1)

swap(mylist, 0, 3)

print(mylist)

In the above example, the if block checks if the same index has been given, in which case there will be no any need for performing the swap operation. 

The line i, j = min(i, j), max(i, j) ensures that, inside the swap function, i will always hold the minimum of the two positions and j the maximum. This is necessary to ensures consistency when swapping the elements because the size of the list will change when we call pop() or insert() which will affect the two positions.

We then call the pop() method twice to remove the two values from the list, we use pop(j-1) because  the size of the list will shrink by one when we call the method the first time i.e pop(i)

Lastly, we re-insert the values at the swapped positions in the list.

Besides all the apparent overheads, this method is far more inefficient  than the previous two due to the shrinking and expanding of the list. These can especially be evident when a lot of swap operations are carried out such as when sorting a large list.