Reverse All Strings in String List in Python
We are given a list of strings and our task is to reverse each string in the list while keeping the order of the list itself unchanged. For example, if we have a list like this: ['gfg', 'is', 'best'] then the output will be ['gfg', 'si', 'tseb'].
Using For Loop
We can use a for loop to iterate over the list and reverse each string. This method is easy to understand and very readable.
a = ["apple", "banana", "cherry", "date"]
res = []
for s in a:
res.append(s[::-1])
print(res)
Output
['elppa', 'ananab', 'yrrehc', 'etad']
Explanation: We iterate over each string s in list a and reverse it using slicing (s[::-1]), then append the reversed string to res list.
Using List comprehension
List comprehension is a concise and efficient way to reverse all strings in a list. It allows us to iterate over the list and apply a transformation to each element.
a = ["apple", "banana", "cherry", "date"]
res = [s[::-1] for s in a]
print(res)
Output
['elppa', 'ananab', 'yrrehc', 'etad']
Explanation: list comprehension iterates over each string in a and for each string s[::-1] reverses each string.
Using map() Function
map() function provides a way to applying a function to all elements of an iterable. In this case, we can use map() with a lambda function to reverse each string.
a = ["apple", "banana", "cherry", "date"]
res = list(map(lambda s: s[::-1], a))
print(res)
Output
['elppa', 'ananab', 'yrrehc', 'etad']
Explanation:
- map() function applies lambda function lambda s: s[::-1] to each string in the list a.
- lambda s: s[::-1] reverses each string.
- list() function is used to convert the result from a map object into a list.
Reverse Strings Without String Slicing
This method avoids string slicing and instead uses string concatenation to reverse each string in the list. It’s a straightforward way to manually reverse strings using loops
a = ["apple", "banana", "cherry", "date"]
for i in range(len(a)):
temp = ''
for ch in a[i]:
temp = ch + temp
a[i] = temp
print(a)
Output
['elppa', 'ananab', 'yrrehc', 'etad']
Explanation:
- We iterate over each string in the list strings.
- For each string, we build its reverse by prepending each character to an empty string temp.
- The reversed string replaces the original string in the list.
Related Articles: