Open In App

Python – Swap elements in String list

Last Updated : 08 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 comprehension The combination of above functionalities can be used to perform this task. In this, we iterate through list using list comprehension and task of swapping is performed using replace(). 

Python3




# Python3 code to demonstrate
# Swap elements in String list
# using replace() + list comprehension
 
# Initializing list
test_list = ['Gfg', 'is', 'best', 'for', 'Geeks']
 
# printing original lists
print("The original list is : " + str(test_list))
 
# Swap elements in String list
# using replace() + list comprehension
res = [sub.replace('G', '-').replace('e', 'G').replace('-', 'e') for sub in test_list]
 
# printing result
print ("List after performing character swaps : " + str(res))


Output : 

The original list is : ['Gfg', 'is', 'best', 'for', 'Geeks']
List after performing character swaps : ['efg', 'is', 'bGst', 'for', 'eGGks']

Time Complexity: O(n) 
Auxiliary Space: O(n)

 Method #2 : Using join() + replace() + split() The combination of above methods can also be used to perform this task. In this, the task of replace is same, but we use join() and split() with same parameter to perform task of list comprehension. 

Python3




# Python3 code to demonstrate
# Swap elements in String list
# using replace() + join() + split()
 
# Initializing list
test_list = ['Gfg', 'is', 'best', 'for', 'Geeks']
 
# printing original lists
print("The original list is : " + str(test_list))
 
# Swap elements in String list
# using replace() + join() + split()
res = ", ".join(test_list)
res = res.replace("G", "_").replace("e", "G").replace("_", "e").split(', ')
 
# printing result
print ("List after performing character swaps : " + str(res))


Output : 

The original list is : ['Gfg', 'is', 'best', 'for', 'Geeks']
List after performing character swaps : ['efg', 'is', 'bGst', 'for', 'eGGks']

Time Complexity: O(n) 
Auxiliary Space: O(n)

Method #3 : Using regex
This task can also be performed using regex. We use sub() method which is used to perform search and replace operation and replace one character with other using regex.
 

Python3




# Python3 code to demonstrate
# Swap elements in String list
# using regex
 
# Initializing list
import re
 
test_list = ['Gfg', 'is', 'best', 'for', 'Geeks']
 
# printing original lists
print("The original list is : " + str(test_list))
 
# Swap elements in String list
# using regex
res = [re.sub('-', 'e', re.sub('e', 'G', re.sub('G', '-', sub))) for sub in test_list]
 
 
# printing result
print("List after performing character swaps : " + str(res))


Output

The original list is : ['Gfg', 'is', 'best', 'for', 'Geeks']
List after performing character swaps : ['efg', 'is', 'bGst', 'for', 'eGGks']

Time Complexity: O(n) 
Auxiliary Space: O(n)



Similar Reads

Python Program to Swap Two Elements in a List
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 = 3Output : [19, 65, 23, 90] Input : List = [1, 2, 3, 4, 5], pos1 = 2, pos2 = 5Output : [1, 5, 3, 4, 2] Swap Two Elements in a List using comma assignment Since the positi
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 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 | Convert List of String List to String List
Sometimes while working in Python, we can have problems of the interconversion of data. This article talks about the conversion of list of List Strings to joined string list. Let's discuss certain ways in which this task can be performed. Method #1 : Using map() + generator expression + join() + isdigit() This task can be performed using a combinat
6 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 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
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
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
Python | Convert list of string to list of list
Many times, we come over the dumped data that is found in the string format and we require it to be represented in the actual list format in which it was actually found. This kind of problem of converting a list represented in string format back to la ist to perform tasks is quite common in web development. Let's discuss certain ways in which this
7 min read
Python | Check if given string can be formed by concatenating string elements of list
Given a string 'str' and a list of string elements, write a Python program to check whether given string can be formed by concatenating the string elements of list or not. Examples: Input : str = 'python' lst = ['co', 'de', 'py', 'ks', 'on'] Output : False Input : str = 'geeks' lst = ['for', 'ge', 'abc', 'ks', 'e', 'xyz'] Output : True Approach #1
5 min read
Practice Tags :
three90RightbarBannerImg