Python program to reverse all strings in a list of strings:
In this post, we will learn how to reverse all strings in a list of strings. For that, we can loop over the elements of the list and for each element, i.e. string, we can reverse it.
Reverse a string in python:
The main issue is to reverse a string. For that, we can use string slicing. For example:
given_text = 'Hello'
print(given_text[::-1])
It will print:
olleH
Reverse all strings in a list:
We can loop through the strings in a list and reverse each string in that list.
given_list = ['Hello', 'world', 'welcome']
print(given_list)
modified_list = []
for item in given_list:
modified_list.append(item[::-1])
print(modified_list)
Here,
- we are iterating through the strings in the list, reversing each string and appending it to modified_list.
It will print the below output:
['Hello', 'world', 'welcome']
['olleH', 'dlrow', 'emoclew']
This program can be improved by using list comprehension:
given_list = ['Hello', 'world', 'welcome']
print(given_list)
modified_list = [item[::-1] for item in given_list]
print(modified_list)
It will print the same output.
Using map():
We can also use map. It takes one lambda as the first argument and the list as the second argument.
The below program does that:
given_list = ['Hello', 'world', 'welcome']
print(given_list)
modified_list = list(map(lambda item: item[::-1], given_list))
print(modified_list)
It will print the below output:
['Hello', 'world', 'welcome']
['olleH', 'dlrow', 'emoclew']