Python: How to Swap 2 Elements in a List (2 Approaches)

Updated: June 16, 2023 By: Khue Post a comment

When writing code in Python, there might be cases where you need to exchange the position of 2 elements in a list to achieve a desired outcome or fulfill a particular requirement. This pithy, code-centric article will show you a couple of different ways to do so.

Using a temporary variable

This approach involves using a temporary variable to store the value of one element, swapping the values of the two elements, and then assigning the stored value to the other element.

# Define a list
my_list = ["A", "B", "C", "D", "E", "F"]

# Swap the element at index 2 and the element at index 4
temp = my_list[2]
my_list[2] = my_list[4]
my_list[4] = temp

# Print the result
print(my_list)

Output:

['A', 'B', 'E', 'D', 'C', 'F']

If you have to deal with this task many times, it’s better to define a reusable function like this:

def swap_elements(lst, i, j):
    temp = lst[i]
    lst[i] = lst[j]
    lst[j] = temp

This technique is simple, intuitive, and easy to understand. It also works for any type of element, even if they are not hashable or mutable.

Using tuple unpacking

This Pythonic solution involves using tuple unpacking to directly swap the values of the two elements without needing a temporary variable. The general syntax is as follows:

lst[i], lst[j] = lst[j], lst[i]

Example:

my_list = ["sling", "arrow", "bow", "academy"]

# Swap the element at index 1 and the last element
my_list[1], my_list[-1] = my_list[-1], my_list[1]
print(my_list)

Output:

['sling', 'academy', 'bow', 'arrow']

Conclusion

You’ve learned more than one approach to swapping 2 elements in a list. Both of them are concise and elegant. Choose the one you prefer to go with. Happy coding & have a nice day!