Length of words in a sentence as tuples in Python


This Python code splits a sentence into words and creates a tuple called word_lengths, where each element of the tuple corresponds to the length of a 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 string "This is a sample sentence."
  • word_lengths = tuple(len(word) for word in sentence.split()): This line of code initializes a variable named word_lengths and assigns it a tuple created using a generator expression.
    • for word in sentence.split(): This part of the code uses a generator expression to iterate through each word word in the sentence. It does this by splitting the sentence into words using sentence.split(), which splits the sentence based on spaces (the default separator).
    • len(word): For each word in the sentence, it calculates the length of the word using the len() function.
    • tuple(...): This surrounds the generator expression and converts the generated word lengths into a tuple.
  • print(sentence): This line of code prints the original sentence to the console.
  • print(word_lengths): This line of code prints the word_lengths tuple (which contains the lengths of the words in the sentence) to the console.

Source Code

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

Output

This is a sample sentence
(4, 2, 1, 6, 8)

Example Programs