Create a list of lengths of words in a sentence


This Python code analyzes a sentence and creates a list called word_lengths using a list comprehension to store the lengths of each word in the sentence. 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."
  • word_lengths = [len(word) for word in sentence.split()]: This line of code initializes a variable named word_lengths 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.
    • len(word): For each word in the list, this expression calculates the length of the word using the len() function.
    • [len(word) for word in sentence.split()]: This is the list comprehension itself. It iterates through the list of words and, for each word, calculates its length and includes it in the new list.
  • print(sentence): This line of code prints the original sentence to the console.
  • print(word_lengths): This line of code prints the word_lengths list to the console.

Source Code

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

Output

This is a sample sentence.
[4, 2, 1, 6, 9]

Example Programs