Using Python’s built-in functions and lists, swapping two elements of a list can be achieved with just a few lines of code. Here’s how to do it:
This short tutorial will demonstrate the process of swapping two specific items in an array or list using Python. You will learn about the different methods available for this purpose, and how they wo …
This short tutorial will demonstrate the process of swapping two specific items in an array or list using Python. You will learn about the different methods available for this purpose, and how they work under the hood.
Swapping Elements in a List Using Indexing
Lists in python are mutable which means we can change them at any point of time. We can swap two elements in a list by using indexing which provides access to elements in the list by their position.
list1 = [1, 2, 3]
# Swapping element at index 0 and 1
list1[0], list1[1] = list1[1], list1[0]
print(list1) # Output: [2, 1, 3]
The code above swaps the first two elements of list1
. The left side of the assignment operator (=
) is a tuple where the first element is the index you want to change and the second one is the value you want to assign to that index. Python evaluates these expressions from right to left, so it first computes list[1], list[0]
(which gives [2, 1]
) then replaces the original first two elements of list
with this new tuple ([2, 1]
, which gives [1, 2, 3]
).
Swapping Elements in a List Using Built-in Functions
Lists also have built-in methods that can be used for swapping. Here are some examples:
list2 = [4, 5, 6]
list2[0], list2[1] = list2[1], list2[0] # Same as previous example using indexing
print(list2) # Output: [5, 4, 6]
Same way we can also use pop()
and insert()
functions to swap elements. Here is an example:
list3 = [7, 8, 9]
list3.insert(0, list3.pop()) # Moves the last element to the first position
print(list3) # Output: [9, 7, 8]
The pop()
method removes and returns the last item of a list. The insert()
method inserts an item at the given index. In this example, we use these methods to move the last element of the list (which is now first) to its original position.