Swap elements in String list - Python
Last Updated :
17 Apr, 2025
Swapping elements in a string list means we need to exchange one element with another throughout the entire string list in Python. This can be done using various methods, such as using replace(), string functions, regular expressions (Regex), etc. For example, consider the original list: ['Gfg', 'is', 'best', 'for', 'Geeks']. After performing swap, the list becomes: ['efg', 'is', 'bGst', 'for', 'eGGks'].
Using Replace
This method uses Python’s replace() function to swap characters in each string of the list. It replaces one character with another and can be applied iteratively on each element.
Python
a = ['Gfg', 'is', 'best', 'for', 'Geeks']
print(str(a))
res = [sub.replace('G', '-').replace('e', 'G').replace('-', 'e') for sub in a]
print (str(res))
Output['Gfg', 'is', 'best', 'for', 'Geeks']
['efg', 'is', 'bGst', 'for', 'eGGks']
Explanation: In this code, the replace() function is chained to replace 'G' with '-', 'e' with 'G', and '-' with 'e'. The list comprehension applies this transformation to each element of the list, and the result is stored in the res list. The original and transformed lists are printed before and after the operation.
Using String Functions
This method uses Python's string manipulation functions like join(), replace(), and split() to perform the element swap. The list is first joined into a string, transformed, and then split back into a list.
Python
a = ['Gfg', 'is', 'best', 'for', 'Geeks']
print(str(a))
res = ", ".join(a)
res = res.replace("G", "_").replace("e", "G").replace("_", "e").split(', ')
print (str(res))
Output['Gfg', 'is', 'best', 'for', 'Geeks']
['efg', 'is', 'bGst', 'for', 'eGGks']
Explanation: The code joins the list into a single string using ", ".join(a). It then applies replace() to swap characters ('G' to '', 'e' to 'G', and '' to 'e'). Finally, the string is split back into a list using split(', '), and the result is stored in res. This method is efficient for handling string-based swaps in a list.
Using RegEx
This method uses regular expressions (RegEx) to perform the character swaps within the list elements. It's a more advanced approach suited for complex pattern-based replacements.
Python
import re
a = ['Gfg', 'is', 'best', 'for', 'Geeks']
print(str(a))
res = [re.sub('-', 'e', re.sub('e', 'G', re.sub('G', '-', sub))) for sub in a]
print(str(res))
Output['Gfg', 'is', 'best', 'for', 'Geeks']
['efg', 'is', 'bGst', 'for', 'eGGks']
Explanation: The code utilizes the re.sub() function, applying nested substitutions to first replace 'G' with '-', then 'e' with 'G', and finally '-' with 'e'. This RegEx-based approach allows for more flexible and powerful pattern matching and substitution, especially when dealing with more complex replacement scenarios. The result is stored in res and printed.
Related Articles:
Similar Reads
List of strings in Python A list of strings in Python stores multiple strings together. In this article, weâll explore how to create, modify and work with lists of strings using simple examples.Creating a List of StringsWe can use square brackets [] and separate each string with a comma to create a list of strings.Pythona =
2 min read
Python | Alternate Sort in String list Sometimes, while working with Python list, we can have a problem in which we need to perform sorting only of alternatively in list. This kind of application can come many times. Let's discuss certain way in which this task can be performed. Method : Using join() + enumerate() + generator expression
2 min read
Python | Consecutive element swapping in String Sometimes, while working with strings, we can have a problem in which we may require to perform swapping of consecutive elements in string. Let's discuss certain ways in which this task can be performed. Method #1 : Using join() + zip() + generator expression The combination of above functions can b
3 min read
Swap tuple elements in list of tuples - Python The task of swapping tuple elements in a list of tuples in Python involves exchanging the positions of elements within each tuple while maintaining the list structure. Given a list of tuples, the goal is to swap the first and second elements in every tuple. For example, with a = [(3, 4), (6, 5), (7,
3 min read
Python - Convert case of elements in a list of strings In Python, we often need to convert the case of elements in a list of strings for various reasons such as standardizing input or formatting text. Whether it's converting all characters to uppercase, lowercase, or even swapping cases. In this article, we'll explore several methods to convert the case
3 min read
Python Program to Swap Two Elements in a List In this article, we will explore various methods to swap two elements in a list in Python. The simplest way to do is by using multiple assignment.Example:Pythona = [10, 20, 30, 40, 50] # Swapping elements at index 0 and 4 # using multiple assignment a[0], a[4] = a[4], a[0] print(a)Output[50, 20, 30,
1 min read
Python - Remove similar index elements in Strings Given two strings, removed all elements from both, which are the same at similar index. Input : test_str1 = 'geels', test_str2 = 'beaks' Output : gel, bak Explanation : e and s are removed as occur in same indices. Input : test_str1 = 'geeks', test_str2 = 'geeks' Output : '', '' Explanation : Same s
6 min read
Python | Rear elements from Tuple Strings Yet another peculiar problem that might not be common, but can occur in python programming while playing with tuples. Since tuples are immutable, they are difficult to manipulate and hence knowledge of possible variation solutions always helps. This article solves the problem of extracting only the
5 min read
Python | Sort each String in String list Sometimes, while working with Python, we can have a problem in which we need to perform the sort operation in all the Strings that are present in a list. This problem can occur in general programming and web development. Let's discuss certain ways in which this problem can be solved. Method #1 : Usi
4 min read
Python | Scramble strings in list Sometimes, while working with different applications, we can come across a problem in which we require to shuffle all the strings in the list input we get. This kind of problem can particularly occur in gaming domain. Let's discuss certain ways in which this problem can be solved. Method #1 : Using
5 min read