Create a list of strings with uppercase first letters


This Python code takes a list of strings, capitalizes the first letter of each word in each string, and stores the capitalized words in a new list called capitalized_words. 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.
  • capitalized_words = [word.capitalize() for word in strings]: This line of code initializes a variable named capitalized_words 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.capitalize(): For each string in the list, this expression uses the capitalize() method to capitalize the first letter of the string. The capitalize() method makes the first character of the string uppercase while making all other characters in the string lowercase.
    • [word.capitalize() for word in strings]: This is the list comprehension itself. It iterates through the strings in the strings list, capitalizes the first letter of each word in each string, and includes the capitalized words in the new list.
  • print(strings): This line of code prints the original strings list to the console.
  • print(capitalized_words): This line of code prints the capitalized_words list to the console.

Source Code

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

Output

['apple', 'banana', 'cherry']
['Apple', 'Banana', 'Cherry']

Example Programs