Python Program to Swap Two Elements in a List

1. Introduction

Swapping two elements in a list is a fundamental operation in computer science, often used in sorting algorithms and data manipulation tasks. 

Swapping refers to the action of taking two positions in a list (or array) and exchanging their contents. This operation is often used to rearrange lists or during algorithms that require elements to change places, like bubble sort or quicksort.

2. Program Steps

1. Define the list and the indices of the elements to be swapped.

2. Use tuple unpacking to swap the elements at these indices.

3. Verify the list after the swap.

3. Code Program

# Function to swap two elements in a list
def swap_elements(a_list, index1, index2):
    # Swap the elements using tuple unpacking
    a_list[index1], a_list[index2] = a_list[index2], a_list[index1]
    return a_list

# List to perform the swap on
my_list = [23, 65, 19, 90]
# Indices of the elements to swap
index1, index2 = 1, 3
# Call the function and print the modified list
swapped_list = swap_elements(my_list, index1, index2)
print(f"List after swapping: {swapped_list}")

Output:

List after swapping: [23, 90, 19, 65]

Explanation:

1. swap_elements is a function that takes a list a_list and two indices index1 and index2.

2. Inside the function, the elements at positions index1 and index2 are swapped using tuple unpacking.

3. my_list is initially defined with 4 elements.

4. index1 and index2 are set to 1 and 3, representing the positions of the elements to swap.

5. The swap_elements function is called with my_list, index1, and index2.

6. After the swap, the function returns the modified list, and it is printed, showing that the elements at positions 1 and 3 have been swapped.

Comments