The most efficient way to swap two list elements in Python is to use the “multiple assignment” method. It exchanges the values at the specified indices. The values of original_list[i] and original_list[j] will be swapped. Here, i and j are indices.
# Initialize the list
num_list = [6, 12, 18, 24, 30]
print("Original List:", num_list)
# Output: Original List: [6, 12, 18, 24, 30]
# Define the indices of the elements to swap
i, j = 1, 4
# Swap the elements at indices 'i' and 'j'
num_list[i], num_list[j] = num_list[j], num_list[i]
print("Swapped List:", num_list)
# Output: Swapped List: [6, 30, 18, 24, 12]
You can see that we swapped elements 12 and 30 based on their indices, and in the output list, 30 appears first, and 12 is the last element.
Lists are mutable, so swaps affect the original list. Elements can be any type (integers, strings, objects), and swapping exchanges references, not copying contents.
Alternate Ways
Approach 1: Using a temporary variable
We can use a temporary variable to hold the value of the first element, then swap the first element with the second one, and finally place the original first element in the second position.
# Initialize the list
num_list = [6, 12, 18, 24, 30]
print("Original List:", num_list)
# Output: Original List: [6, 12, 18, 24, 30]
# Define the indices of the elements to be swapped
i, j = 0, 1
# Use a temporary variable to hold the value of the first elements
temp = num_list[i]
num_list[i] = num_list[j]
num_list[j] = temp
print("Swapped List:", num_list)
# Output: Swapped List: [12, 6, 18, 24, 30]
Approach 2: Using a list.pop() Method
We can use the pop() method to remove elements at indices i and j, and then use the insert() method to swap the positions of both elements.
# Initialize the list with integers
num_list = [6, 12, 18, 24, 30]
print("Original List:", num_list)
# Output: [6, 12, 18, 24, 30]
# Define the indices of the elements to be swapped
i, j = 1, 4
# Remove the element at index 'i' and 'j - 1'
# (adjusted due to the previous pop) and store it
element_i = num_list.pop(i)
element_j = num_list.pop(j - 1)
num_list.insert(i, element_j)
num_list.insert(j, element_i)
# Print the list after swapping the elements
print("Swapped List:", num_list)
# Output: [6, 30, 18, 24, 12]
That’s it!



