Create a list of strings with characters in uppercase


This Python code takes a list of strings and creates a new list called uppercase_strings using a list comprehension. The new list contains the same words, but each word is converted to uppercase using the upper() method. Here's how the code works:

  • strings = ["apple", "banana", "cherry"]: This line initializes a variable named strings and assigns it a list containing three strings.
  • uppercase_strings = [word.upper() for word in strings]: This line of code initializes a variable named uppercase_strings and assigns it the result of a list comprehension.
    • for word in strings: This part sets up a loop that iterates through each string word in the strings list.
    • word.upper(): For each string in the list, this expression uses the upper() method to convert the entire string to uppercase. The upper() method changes all lowercase characters in the string to their uppercase equivalents.
    • [word.upper() for word in strings]: This is the list comprehension itself. It iterates through the strings in the strings list, converts each string to uppercase, and includes the uppercase strings in the new list.
  • print(strings): This line of code prints the original strings list to the console.
  • print(uppercase_strings): This line of code prints the uppercase_strings list to the console.

Source Code

strings = ["apple", "banana", "cherry"]
uppercase_strings = [word.upper() for word in strings]
print(strings)
print(uppercase_strings)

Output

['apple', 'banana', 'cherry']
['APPLE', 'BANANA', 'CHERRY']

Example Programs