Open In App

Python Program to Swap Two Elements in a List

Last Updated : 03 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a list in Python and provided the positions of the elements, write a program to swap the two elements in the list. 

Examples:  

Input : List = [23, 65, 19, 90], pos1 = 1, pos2 = 3
Output : [19, 65, 23, 90]

Input : List = [1, 2, 3, 4, 5], pos1 = 2, pos2 = 5
Output : [1, 5, 3, 4, 2]

Swap Two Elements in a List using comma assignment 

Since the positions of the elements are known, we can simply swap the positions of the elements. 

Python3




# Python3 program to swap elements
# at given positions
 
# Swap function
def swapPositions(list, pos1, pos2):
     
    list[pos1], list[pos2] = list[pos2], list[pos1]
    return list
 
# Driver function
List = [23, 65, 19, 90]
pos1, pos2  = 1, 3
 
print(swapPositions(List, pos1-1, pos2-1))


Output: 
 

[19, 65, 23, 90]

Time Complexity: O(1), for using constant operations.
Auxiliary Space: O(1), for using constant extra space.

Using Inbuilt list.pop() function to Swap Two Elements in a List

Pop the element at pos1 and store it in a variable. Similarly, pop the element at pos2 and store it in another variable. Now insert the two popped element at each other’s original position. 

Python3




# Python3 program to swap elements
# at given positions
 
# Swap function
def swapPositions(list, pos1, pos2):
     
    # popping both the elements from list
    first_ele = list.pop(pos1)  
    second_ele = list.pop(pos2-1)
    
    # inserting in each others positions
    list.insert(pos1, second_ele) 
    list.insert(pos2, first_ele) 
     
    return list
 
# Driver function
List = [23, 65, 19, 90]
pos1, pos2  = 1, 3
 
print(swapPositions(List, pos1-1, pos2-1))


Output: 
 

[19, 65, 23, 90]

Time Complexity: O(1), for using constant operations.
Auxiliary Space: O(1), for using constant extra space.

Swap Two Elements in a List Using tuple variable

Store the element at pos1 and pos2 as a pair in a tuple variable, say get. Unpack those elements with pos2 and pos1 positions in that list. Now, both the positions in that list are swapped. 

Python3




# Python3 program to swap elements at
# given positions
 
# Swap function
def swapPositions(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 = [23, 65, 19, 90]
 
pos1, pos2  = 1, 3
print(swapPositions(List, pos1-1, pos2-1))


Output: 
 

[19, 65, 23, 90]

Time Complexity: O(1), for using constant operations.
Auxiliary Space: O(1), for using constant extra space.

Swap Two Elements in a List Using temp variable

Python3




# Python3 program to swap elements
# at given positions
 
# Swap function
def swapPositions(lis, pos1, pos2):
    temp=lis[pos1]
    lis[pos1]=lis[pos2]
    lis[pos2]=temp
    return lis
# Driver function
List = [23, 65, 19, 90]
pos1, pos2 = 1, 3
 
print(swapPositions(List, pos1-1, pos2-1))


Output

[19, 65, 23, 90]

Time Complexity: O(1), for using constant operations.
Auxiliary Space: O(1), for using constant extra space.

Swap Two Elements in a List Using enumerate

Another approach to swapping elements in a list is to use the enumerate function to get the index and value of each element in the list, and then use a loop to find the elements that need to be swapped and swap them.

Python3




def swapPositions(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 = [23, 65, 19, 90]
pos1, pos2 = 1, 3
print(swapPositions(List, pos1-1, pos2-1))
#This code is contributed by Edula Vinay Kumar Reddy


Output

[19, 65, 23, 90]

This approach has a time complexity of O(n), since it involves looping through the entire list to find the elements to be swapped. The space complexity is O(1), since it only uses a constant amount of additional space to store the elements to be swapped.

Note that this approach can be made more efficient by using a single loop and breaking out of the loop once the elements have been found and swapped.



Previous Article
Next Article

Similar Reads

Python program to Swap i'th with j'th elements in List
Given a list, the task is to write a Python program to the given list of elements, toggle every i and j elements in the list. Examples: Input : test_list = [4, 7, 8, 0, 8, 4, 2, 9, 4, 8, 4], i, j = 4, 8 Output : [8, 7, 4, 0, 4, 8, 2, 9, 8, 4, 8] Explanation : 4 is swapped by 8 at each occurrence. Input : test_list = [4, 7, 8, 0, 8, 4], i, j = 4, 8
4 min read
Python Program to Swap Two Variables
Given two variables x and y, write a Python program to swap their values. Let's see different methods in Python to do this task. Method 1: Using Naive approachThe most naive approach is to store the value of one variable(say x) in a temporary variable, then assigning the variable x with the value of variable y. Finally, assign the variable y with t
3 min read
Python Program to swap two numbers without using third variable
Given two variables n1 and n2. The task is to swap the values of both the variables without using third variable.Examples: X : 10 Y : 20 After swapping X and Y, we get : X : 20 Y : 10 A : 'Hello' B : 'World' After swapping A and B, we get : A : 'World' B : 'Hello' Method 1 :- Using simple built-in method left , right = right , left This method work
4 min read
Python | Swap tuple elements in list of tuples
While doing competitive programming, one can come across a question in which one requires to work with 2D plane and work with coordinates. One such subproblem can be swapping x, y coordinate elements. Let's discuss certain ways in which this problem can be solved using tuple element swapping. Method #1 : Using list comprehension This is just a brut
4 min read
Python - Swap elements in String list
Sometimes, while working with data records we can have a problem in which we need to perform certain swap operation in which we need to change one element with other over entire string list. This has application in both day-day and data Science domain. Lets discuss certain ways in which this task can be performed. Method #1 : Using replace() + list
3 min read
Python program to Swap Keys and Values in Dictionary
Dictionary is quite a useful data structure in programming that is usually used to hash a particular key with value so that they can be retrieved efficiently. Let’s discuss various ways of swapping the keys and values in Python Dictionary. Method#1 (Does not work when there are multiple same values): One naive solution maybe something like just swa
4 min read
Python Program to swap the First and the Last Character of a string
Given a String. The task is to swap the first and the last character of the string. Examples: Input: GeeksForGeeks Output: seeksForGeekG Input: Python Output: nythoP Python string is immutable which means we cannot modify it directly. But Python has string slicing which makes it very easier to perform string operations and make modifications. Follo
2 min read
Python Program to Swap dictionary item's position
Given a Dictionary, the task is to write a python program to swap positions of dictionary items. The code given below takes two indices and swap values at those indices. Input : test_dict = {'Gfg' : 4, 'is' : 1, 'best' : 8, 'for' : 10, 'geeks' : 9}, i, j = 1, 3 Output : {'Gfg': 4, 'for': 10, 'best': 8, 'is': 1, 'geeks': 9} Explanation : (for : 10)
4 min read
How to Swap Two Rows in a NumPy Array
One common task you might encounter when working with NumPy arrays is the need to swap two rows. Swapping rows can be essential in data preprocessing, reshaping data, or reordering data to perform specific analyses in Python. In this article, we will explore different methods to swap two rows in a NumPy array. In this article, we will see how to sw
4 min read
Swap Two Variables in One Line
We have discussed different approaches to swap two integers without the temporary variable. How to swap into a single line without using the library function?1) Python: In Python, there is a simple and syntactically neat construct to swap variables, we just need to write "x, y = y, x".2) C/C++: Below is one generally provided classical solution: //
4 min read
three90RightbarBannerImg