Swapping elements between two indices in python list.

In this tutorial, we will discuss how to swap the elements at two given positions in python list. …

Updated October 20, 2023

In this tutorial, we will discuss how to swap the elements at two given positions in python list.

Swapping is often used for certain applications like swapping data, sorting, etc., but it can also be done by just assigning them to each other, as long as you remember which way around they are. In Python, we do this through index assignment. Here’s a simple example of swapping elements in list:

list_a = [1, 2, 3, 4, 5]
list_b = ['a', 'b', 'c']
print(f"Before Swapping: {list_a}, {list_b}")

#Swap elements at index 0 and 4 in list_a
list_a[0], list_a[4] = list_a[4], list_a[0]

#Swap elements at index 1 and 2 in list_b
list_b[1], list_b[2] = list_b[2], list_b[1]

print(f"After Swapping: {list_a}, {list_b}")

This will output: Before Swapping: [1, 2, 3, 4, 5], [‘a’, ‘b’, ‘c’] After Swapping: [5, 2, 3, 4, 1], [‘b’, ‘c’, ‘a’]

As you can see, we have swapped the elements at specific indices. This is done in-place and doesn’t require any additional storage space.

Stay up to date on the latest in Coding Python with AI and Data Science

Intuit Mailchimp