Tuple of distinct words with length greater than 4 in a sentence in Python


This Python code processes the sentence and creates a tuple called long_word_tuples. The long_word_tuples tuple contains words from the sentence that have a length greater than 4 characters. Here's how the code works:

  • sentence = "This is a sample sentence with words of various lengths.": This line initializes a variable named sentence and assigns it the given sentence.
  • long_word_tuples = tuple(word for word in sentence.split() if len(word) > 4): This line initializes a variable named long_word_tuples 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 after splitting it by spaces using sentence.split().
    • if len(word) > 4: For each word, it checks if the length of the word is greater than 4 characters.
    • tuple(...): This surrounds the generator expression and converts the generated words that meet the condition into a tuple.
  • print(sentence): This line of code prints the original sentence to the console.
  • print(long_word_tuples): This line of code prints the long_word_tuples tuple (which contains words from the sentence with a length greater than 4 characters) to the console.

Source Code

sentence = "This is a sample sentence with words of various lengths."
long_word_tuples = tuple(word for word in sentence.split() if len(word) > 4)
print(sentence)
print(long_word_tuples)

Output

This is a sample sentence with words of various lengths.
('sample', 'sentence', 'words', 'various', 'lengths.')

Example Programs