Tuple of words with length greater than 3 in a sentence in Python


This Python code creates a tuple called long_words, which contains words from the sentence string that have more than 3 characters. 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."
  • long_words = tuple(word for word in sentence.split() if len(word) > 3): This line of code initializes a variable named long_words and assigns it a tuple created using a generator expression.
    • for word in sentence.split(): This part of the code sets up a loop that iterates through each word word in the sentence, split by spaces using sentence.split().
    • if len(word) > 3: For each word in the split sentence, it checks if the length of the word (i.e., the number of characters in the word) is greater than 3 using len(word) > 3.
    • word: If a word has more than 3 characters, it includes the word in the generator expression.
    • tuple(...): This surrounds the generator expression and converts the generated words into a tuple.
  • print(sentence): This line of code prints the original sentence to the console.
  • print(long_words): This line of code prints the long_words tuple (which contains words with more than 3 characters) to the console.

Source Code

sentence = "This is a sample sentence"
long_words = tuple(word for word in sentence.split() if len(word) > 3)
print(sentence)
print(long_words)

Output

This is a sample sentence
('This', 'sample', 'sentence')

Example Programs