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 of elements in a list of strings.
Using List Comprehension
List comprehension is one of the most efficient ways to process each element in a list. It allows us to create a new list by applying a function (such as lower()
or upper()
) to each string in the original list in a concise and readable manner.
s1 = ['Geeks', 'for', 'Geeks']
#lower strings
s2 = [s.lower() for s in s1]
print(s2)
Output
['geeks', 'for', 'geeks']
Explanation:
- We use list comprehension to iterate over each element s in the list
s1
. - The method
lower()
is applied to each string to convert it to lowercase. - This method is fast and directly applies the transformation to each string.
Let's explore some more methods and see how we can convert the case of elements in a list of strings.
Table of Content
Using map()
map()
function is another efficient method for applying a function to every element in an iterable. It returns an iterator, and when combined with list()
, we can create a new list after converting the case of the strings.
s1 = ['Geeks', 'for', 'Geeks']
s2 = list(map(str.lower, s1))
print(s2)
Output
['geeks', 'for', 'geeks']
Explanation:
- The
map()
function appliesstr.lower
to each string in the lists1
. - The result is then converted to a list using
list()
. - This method is similar to list comprehension but uses an iterator, making it a bit more memory-efficient for large lists.
Using For Loop
Using a simple for
loop is another approach, though it's a bit slower because we manually iterate and apply the function to each element.
s1 = ['Python', 'is', 'fun!']
s2 = []
for s in s1:
s2.append(s.lower())
print(s1)
Output
['Python', 'is', 'fun!']
Explanation:
- We initialize an empty list
s2
. - Using a
for
loop, we iterate through each strings
in thes1
list. - The method
lower()
is applied to each string, and the result is appended to thes2
list.
Using append()
(Manual Method)
This method is similar to the previous one but includes a step-by-step breakdown of how we manually append transformed strings into a new list. It's the least efficient because of the overhead of repeatedly calling append()
and the explicit loop.
s1 = ['Python', 'is', 'fun!']
s2 = []
for s in s1:
s2.append(s.upper())
print(s1)
Output
['Python', 'is', 'fun!']
Explanation:
- We manually iterate over each string in the list
s1
. - The
upper()
method is used to convert each string to uppercase. - Each converted string is appended to the
s2
list.