Python – Swap elements in String list
Last Updated :
08 Mar, 2023
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
test_list = [ 'Gfg' , 'is' , 'best' , 'for' , 'Geeks' ]
print ("The original list is : " + str (test_list))
res = [sub.replace( 'G' , '-' ).replace( 'e' , 'G' ).replace( '-' , 'e' ) for sub in test_list]
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
test_list = [ 'Gfg' , 'is' , 'best' , 'for' , 'Geeks' ]
print ("The original list is : " + str (test_list))
res = ", ".join(test_list)
res = res.replace("G", "_").replace("e", "G").replace("_", "e").split( ', ' )
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
import re
test_list = [ 'Gfg' , 'is' , 'best' , 'for' , 'Geeks' ]
print ( "The original list is : " + str (test_list))
res = [re.sub( '-' , 'e' , re.sub( 'e' , 'G' , re.sub( 'G' , '-' , sub))) for sub in test_list]
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)
Please Login to comment...