Create a list of uppercase words from a sentence


This Python code takes a sentence, splits it into words, and converts each word to uppercase using a list comprehension. Here's how the code works:

  • sentence = "This is a sample sentence.": This line initializes a variable named sentence and assigns it the value "This is a sample sentence."
  • uppercase_words = [word.upper() for word in sentence.split()]: This line of code initializes a variable named uppercase_words and assigns it the result of a list comprehension.
    • sentence.split(): This part of the code splits the sentence into a list of words. By default, it splits the sentence on whitespace, so it separates the words.
    • for word in sentence.split(): This part sets up a loop that iterates through each word in the list of words.
    • word.upper(): For each word in the list, this expression converts it to uppercase using the .upper() method. This method changes all the characters in the string to uppercase.
    • [word.upper() for word in sentence.split()]: This is the list comprehension itself. It iterates through the list of words, converts each word to uppercase, and includes the uppercase word in the new list.
  • print(sentence): This line of code prints the original sentence to the console.
  • print(uppercase_words): This line of code prints the uppercase_words list to the console.

Source Code

sentence = "This is a sample sentence."
uppercase_words = [word.upper() for word in sentence.split()]
print(sentence)
print(uppercase_words)

Output

This is a sample sentence.
['THIS', 'IS', 'A', 'SAMPLE', 'SENTENCE.']

Example Programs