How can I convert a list of strings to uppercase in Python?
Gable E
gable e profile pic

To convert a list of strings to uppercase in Python, you can use a loop or a list comprehension to iterate over each string in the list and apply theupper() method to convert it to uppercase. Theupper() method returns a new string with all characters converted to uppercase. Here's an example of how you can perform this conversion using a loop:

1
2
3
4
5
6
7
8
9
10
11

def convert_to_uppercase(string_list):
    result = []
    for string in string_list:
   result.append(string.upper())
    return result

# Usage:
my_list = ["apple", "banana", "cherry"]
uppercase_list = convert_to_uppercase(my_list)
print(uppercase_list)  # Output: ['APPLE', 'BANANA', 'CHERRY']

In the above code, theconvert_to_uppercase() function takes astring_list parameter representing the list of strings to convert. It initializes an empty list calledresult to store the uppercase strings. The function then iterates over each string in thestring_list using afor loop. Inside the loop, it applies theupper() method to each string, converting it to uppercase. The uppercase string is then appended to theresult list. Finally, theresult list, containing the converted uppercase strings, is returned as the output. Alternatively, you can achieve the same result using a list comprehension, which provides a concise way to transform each element of a list:

1
2
3
4
5
6
7
8

def convert_to_uppercase(string_list):
    return [string.upper() for string in string_list]

# Usage:
my_list = ["apple", "banana", "cherry"]
uppercase_list = convert_to_uppercase(my_list)
print(uppercase_list)  # Output: ['APPLE', 'BANANA', 'CHERRY']

In this code, theconvert_to_uppercase() function uses a list comprehension to create a new list. It iterates over each string in thestring_list, applies theupper() method to convert it to uppercase, and returns the resulting list of uppercase strings directly. Both approaches allow you to convert a list of strings to uppercase in Python. They provide flexibility and efficiency, enabling you to work with string data in a transformed format.