The Wayback Machine - https://web.archive.org/web/20240927195212/https://www.geeksforgeeks.org/python-program-to-swap-two-elements-in-a-list/
Open In App

Python Program to Swap Two Elements in a List

Last Updated : 26 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

Example: Swap Two Elements in a List using a comma assignment.

Python
my_list = [10, 20, 30, 40, 50]

# Swap elements at index 1 and 3
pos1, pos2 = 1, 3  

# Swap the elements
my_list[pos1], my_list[pos2] = my_list[pos2], my_list[pos1]

print("List after swapping:", my_list)

Output

List after swapping: [10, 40, 30, 20, 50]

Switch Position of Two Items in a Python list using Temp Variable

This code defines a function swapPositions that swaps two elements in a list using their positions. The Driver function demonstrates swapping elements at specified positions in the list.

Python
# 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 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. 

Python
# 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 Inbuilt list.pop()

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. 

Python
# 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.

Python Program to 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.

Python
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 : 10Y : 20 After swapping X and Y, we get :X : 20Y : 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 works fo
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 operations in which we need to change one element with another over the entire string list in Python. Example This code takes a list of strings and performs a character swap where 'G' is replaced by 'e', and 'e' is replaced by 'G'. This is achi
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
NumPy ndarray.byteswap() Method | Swap bytes of the Array Elements
The ndarray.byteswap() method swaps the bytes of the array elements. It toggles between low-endian and big-endian data representation by returning a byteswapped array, optionally swapped in-place. Note: byteswap() method does not work on arrays of strings. Example C/C++ Code # Python program explaining # byteswap() function import numpy as geek # a
2 min read
Python | Subtract two list elements if element in first list is greater
Given two list, If element in first list in greater than element in second list, then subtract it, else return the element of first list only.Examples: Input: l1 = [10, 20, 30, 40, 50, 60] l2 = [60, 50, 40, 30, 20, 10] Output: [10, 20, 30, 10, 30, 50] Input: l1 = [15, 9, 10, 56, 23, 78, 5, 4, 9] l2 = [9, 4, 5, 36, 47, 26, 10, 45, 87] Output: [6, 5,
5 min read
Python3 Program for Swap characters in a String
Given a String S of length N, two integers B and C, the task is to traverse characters starting from the beginning, swapping a character with the character after C places from it, i.e. swap characters at position i and (i + C)%N. Repeat this process B times, advancing one position at a time. Your task is to find the final String after B swaps. Exam
5 min read
Python3 Program for Block swap algorithm for array rotation
Write a function rotate(ar[], d, n) that rotates arr[] of size n by d elements.  Rotation of the above array by 2 will make array Algorithm :  Initialize A = arr[0..d-1] and B = arr[d..n-1]1) Do following until size of A is equal to size of B a) If A is shorter, divide B into Bl and Br such that Br is of same length as A. Swap A and Br to change AB
3 min read
Python Program that prints elements common at specified index of list elements
Given a list of strings, the task is to write a Python program to extract all characters that are same at a specified index of each element of a list. Illustration: Input : test_list = ["geeks", "weak", "beak", "peek"] Output : ['e', 'k'] Explanation : e and k are at same at an index on all strings.Input : test_list = ["geeks", "weak", "beak", "pee
5 min read
Python program to print elements which are multiples of elements given in a list
Given a list, the task here is to write a Python program to extract elements which are multiple of all elements of custom list. Input : test_list = [4, 24, 8, 10, 12, 23], div_list = [6, 4] Output : [24, 12] Explanation : 24 and 12 divides 6 and 4 both. Input : test_list = [4, 24, 8, 10, 12, 23], div_list = [6, 4, 7] Output : [] Explanation : No el
5 min read
Python Program to get Maximum product of elements of list in a 2D list
Given lists in a list, the task is to write a Python program to find the maximum product of elements of list in a Python 2D list. Examples: Input : [[1, 2, 3], [4, 5, 6], [7, 8, 9]] Output : 504 Explanation:1*2*3 = 6, 4*5*6 = 120, 7*8*9 = 504 Since maximum is 504. Input : [[3, 4], [1, 2, 3], [0, 0]] Output : 12 Explanation:3*4 = 12, 1*2*3 = 6, 0*0
2 min read
Python | Swap commas and dots in a String
The problem is quite simple. Given a string, we need to replace all commas with dots and all dots with the commas. This can be achieved in many different ways. Examples: Input : 14, 625, 498.002Output : 14.625.498, 002 Method 1: Using maketrans and translate() maketrans: This static method returns a translation table usable for str.translate(). Thi
4 min read
Python | Swap Name and Date using Group Capturing in Regex
In this article, we will learn how to swap Name and Date for each item in a list using Group Capturing and Numeric Back-referencing feature in Regex . Capturing Group : Parentheses groups the regex between them and captures the text matched by the regex inside them into a numbered group i.e ([\w ]+) which can be reused with a numbered back-referenc
3 min read
Python - Swap ith and jth key's value in dictionary
Given a dictionary, perform swapping of ith and jth index key's value. Input : test_dict = {"Gfg": 2, "is": 4, "best": 7, "for": 9, "geeks": 10}, i, j = 1, 4 Output : {'Gfg': 2, 'is': 10, 'best': 7, 'for': 9, 'geeks': 4} Explanation : Values of "is" and "geeks" swapped.Input : test_dict = {"Gfg": 2, "is": 4, "best": 7, "for": 9, "geeks": 10}, i, j
6 min read
Python - Swap K suffix with prefix
Given a List, perform a swap of K prefix and suffix. Examples: Input : test_list = [5, 6, 3, 1, 0, 1, 3, 5, 7, 9], K = 2Output : [7, 9, 3, 1, 0, 1, 3, 5, 5, 6]Explanation : Rear 2 and Front 2 elements swapped. Input : test_list = [5, 6, 3, 1, 0, 1, 3, 5, 7, 9], K = 1Output : [9, 6, 3, 1, 0, 1, 3, 5, 7, 5]Explanation : Rear 1 and Front 1 element swa
4 min read
Python | Make pair from two list such that elements are not same in pairs
Given two lists, the task is to create pairs of elements (pairs can be repeated) from two list such that elements are not same in pairs. Examples: Input : list1 = [100, 20, 30, 400] list2 = [400, 2, 30] Output: [[100, 400], [100, 2], [100, 30], [20, 400], [20, 2], [20, 30], [30, 400], [30, 2], [400, 2], [400, 30]] Input: list1 = [10,20,30,40] list2
2 min read
Python | Adding two list elements
There can be many situations in which one requires to find the index-wise summation of two different lists. This can have a possible application in day-day programming. Let's discuss various ways in which this task can be performed in Python. Input: input_list 1 : [1, 3, 4, 6, 8] input _list 2 : [4, 5, 6, 2, 10]Output: output_list[5, 8, 10, 8, 18]E
5 min read
Python | Equate two list index elements
Sometimes we need to link two list from the point of view of their index elements and this kind of problem comes mostly in places where we need to display in formatted form the linkage of two lists with one another. This a very specific problem, but can be useful whenever we need a possible solution. Let's discuss certain ways in which this can be
8 min read
Python | Transpose elements of two dimensional list
Given a two-dimensional list of integers, write a Python program to get the transpose of given list of lists.In Python, a matrix can be interpreted as a list of lists. Each element is treated as a row of the matrix. For example m = [[10, 20], [40, 50], [30, 60]] represents a matrix of 3 rows and 2 columns. First element of the list – m[0] and eleme
3 min read
Python - Nearest occurrence between two elements in a List
Given a list and two elements, x and y find the nearest occurrence index of element x from element y. Input : test_list = [2, 4, 5, 7, 8, 6, 3, 8, 7, 2, 0, 9, 4, 9, 4], x = 4, y = 6 Output : 1 Explanation : 4 is found at 1, 12 and 14th index, 6 is at 5th index, nearest is 1st index.Input : test_list = [2, 4, 5, 7, 8, 6, 3, 8, 7, 2, 0, 9, 4, 9, 4],
5 min read
Remove common elements from two list in Python
Given two lists, the task is to write a Python program to remove all the common elements of two lists. Examples: Input : list1 = [1, 2, 3, 4, 5] list2 = [4, 5, 6, 7, 8,] Output : list1 = [1, 2, 3] list2 = [6, 7, 8] Explanation: Lists after removing common elements of both the lists i.e, 4 and 5. Input : list1 = [1, 2, 3] list2 = [1, 2, 3] Output :
5 min read
How to swap columns of a given NumPy array?
In this article, let's discuss how to swap columns of a given NumPy array. Approach : Import NumPy moduleCreate a NumPy arraySwap the column with IndexPrint the Final array Example 1: Swapping the column of an array. C/C++ Code # importing Module import numpy as np # creating array with shape(4,3) my_array = np.arange(12).reshape(4, 3) print("
2 min read
Pandas DataFrame transpose() Method: Swap Rows and Columns
Pandas DataFrame is a two-dimensional, size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. It can be thought of as a dictionary-like container for the Series objects. This is the primary data structure of the Pandas. Pandas DataFrame transpos
4 min read
Python Program to Print uncommon elements from two sorted arrays
Given two sorted arrays of distinct elements, we need to print those elements from both arrays that are not common. The output should be printed in sorted order. Examples : Input : arr1[] = {10, 20, 30} arr2[] = {20, 25, 30, 40, 50} Output : 10 25 40 50 We do not print 20 and 30 as these elements are present in both arrays. Input : arr1[] = {10, 20
3 min read