Python Program to Swap Two Elements in a List

In programming, swapping elements is a common process. We might occasionally get into circumstances when we need to switch two elements in a list. So, let’s learn how to swap two elements in a list in a Python programming language.

Moving on to further discussion, let’s know about the List.

What is a List in Python?

Lists are a basic data structure in Python that we may use to store and manage collections of objects. It is an organized, mutable collection of elements with a variable length and the ability to store things of various data kinds.

Lists enable actions like index-based access to elements, slicing to extract sublists, element modification, appending and extending, inserting and removing elements, and so forth. They are an essential data structure in Python and are frequently used for storing and working with data collections.

Lists are defined using square brackets ([]).

Example:

my_list = [1, 'Hello', 3.14, True, [5, 6, 7]]

They can be used for a variety of activities, including index-based access, list-slicing to extract sublists, element modification, appending and extending, inserting and removing elements, and element modification.

Let’s understand the problem statement.

In this question, we have to swap two elements from a list using Python. For example, if a list x = [2, 4, 5, 7] and the question asks to swap positions 1 and 3, the output should be [5, 4, 2, 7] after swapping.

In Python, different approaches are present to love this question. Let’s discuss a few approaches to swap two elements from a list.

Approach 1

Using a temp variable, we can easily swap two elements in a Python list.

Here is the code for this approach:

Example:

# Swap function

def swap_pos( l, pos1, pos2 ):

    temp = l[pos1]

    l[pos1] = l[pos2]

    l[pos2] = temp

    return l

# Driver function

List = [ 54, 48, 91, 37]

pos1, pos2 = 1, 3

print(swap_pos(List, pos1-1, pos2-1))

The output of this code is:

Output:

[91, 48, 54, 37]

In this code, a function swap_pos is defined to swap the positions of two members in a list. It accepts a list of l and two locations, pos1 and pos2 as input. Using a temporary variable, the values at positions pos1 and pos2 are switched inside the function. It then sends back the changed list. The swap_pos function is invoked in the driver code with the proper arguments, and the changed result list is displayed.

Approach 2

Using a comma assignment, we can easily swap two elements in a Python list.

In Python, we can assign several variables at once by providing a list of values that are separated by commas. It offers a clear and effective approach to giving values to numerous variables in a single line of code. This functionality is frequently employed when working with functions that return numerous values or when unpacking data structures like tuples or lists.

Let’s see the code for this approach in Python.

Example:

# Swap function

def swap(l, pos1, pos2):

    l[pos1], l[pos2] = l[pos2], l[pos1]

    return l

 # Driver function

List = [23, 65, 19, 90]

pos1, pos2 = 1, 3

print(swap(List, pos1-1, pos2-1))

The output of this code is:

Output:

[19, 65, 23, 90]

In this Python program, a function swap is defined, and it swaps the locations of two members in a provided list. It accepts two indexes, pos1 and pos2, along with a list, l, as input. A single line of code inside the function swaps the values at positions pos1 and pos2 by making use of a comma assignment. It then sends back the changed list.

Approach 3

The third approach to solve this swapping problem in Python is using the Inbuilt list.pop() function.

In this approach, we pop the element at position one and place it in a variable. In a similar manner, pop the element at position two and save it in a different variable. Next, place the two previously popped elements in their original positions.

Let’s see the Python code for this swapping problem in the list.

Example:

# Swap function

def swap_pos(list, pos1, pos2):

    # popping both the elements from list

    first_ele = list.pop(pos1)

    second_ele = list.pop(pos2-1)

    # inserting in each other's positions

    list.insert(pos1, second_ele)

    list.insert(pos2, first_ele)

    return list

# Driver function

List = [ 45, 29, 76, 34]

pos1, pos2 = 2, 3

print(swap_pos(List, pos1-1, pos2-1))

The output of this code is:

Output:

[45, 76, 29, 34]

In this program, a function called swap_pos is defined, and it swaps the locations of two entries in a list. It accepts two places and a list as input. The elements are essentially swapped by being taken from the list at the specified positions using pop and then returned at the other positions using insert inside the function. The function returns the changed list. A driver program that demonstrates the function by swapping the entries at positions 2 and 3 in a provided list is also included in the source. The result will be a modified list with the elements swapped.

Approach 4

In the next approach, let’s see how we can swap two elements in a list with the help of a tuple variable. In this method, we use the ability of tuples to effectively swap the positions of elements in a list.
The elements of the swapped positions should be saved as a pair in a tuple variable. Unpack the elements that are in the list's pos1 and pos2 locations. This way, we can easily switch the two spots on that list.

Here is the code for this approach in Python:

Example:

# Swap function

def swap_pos(list, pos1, pos2):

# Storing the two elements

# As a pair in a tuple variable, get

get = list[pos1], list[pos2]

# unpacking those elements

list[pos2], list[pos1] = get

return list

# Driver Code

List = [26, 15, 83, 67]

pos1, pos2 = 1, 3

print(swap_pos(List, pos1-1, pos2-1))

The output of this code is:

Output:

[83, 15, 26, 67]

This code defines a function swap_pos, which swaps the positions of two entries in a list. It accepts two places and a list as input. The elements in a tuple variable are kept inside the function at the specified locations. Then, using tuple unpacking, the list's elements are switched. Finally, the function returns the changed list. 

The code also includes a driver program to show how the function works by switching the elements at specific locations in a list. The result will be a modified list with the elements swapped.

Approach 5

In this method, we will utilize the enumerate function to switch the places of two elements in a list. We receive the enumerate function's index and the appropriate element during iteration. This allows us to switch the desired components out without using complicated reasoning or additional variables. It illustrates how to use the enumerate function clearly and effectively to swap the elements in a list.

Let’s see the code in Python for this approach to swap the elements in a list.

Example:

def swap_pos(lis, pos1, pos2):

for i, x in enumerate(lis):

if i == pos1:

elem1 = x

if i == pos2:

elem2 = x

lis[pos1] = elem2

lis[pos2] = elem1

return lis

List = [ 49, 28, 43, 51]

pos1, pos2 = 1, 3

print(swap_pos(List, pos1-1, pos2-1))

The output of this code is:

Output:

[43, 28, 49, 51]

The function swap_pos in this code is defined to swap the locations of two members in a list. It accesses the index and the relevant element by iterating through the list using the enumerate function. The code locates the items at the given locations (pos1 and pos2), identifies them, and stores their information in variables (elem1 and elem2). The elements in the list are then swapped by assigning elem1 to pos2 and elem2 to pos1, respectively. The changed list is then finally returned.

A specified list's elements at locations 1 and 3 are switched in the driver program provided, and the resulting list is printed to show how the function works.

We will learn different approaches to solving this Python problem to swap two elements in a list.

Conclusion

Programmers frequently need to swap out list elements, and Python offers a stylish way to do this. We may effectively switch two items in a list using the strength of tuple packing and unpacking.

In this article, we looked at different methods in Python programs to swap two elements in a Python list. The function updates the list in place and returns the new list after receiving the list and the indices of the components to be swapped. Swapping list elements is a useful skill that can be used in various programming situations. Efficiency in swapping list members is a crucial Python programming talent, whether you're handling coding problems, sorting algorithms, or working with data structures.

← Prev Next →