Pairs of distinct words and their lengths, excluding words with lengths not divisible by 3, in a sentence as a tuple in Python


This Python code processes a sentence and creates a tuple named divisible_by_3_length_word_length_tuples. The tuple contains word-length pairs for words in the sentence with a length divisible by 3. Here's how the code works:

  • sentence = "Hello, how are you?": This line initializes a variable named sentence and assigns it a string containing a sentence.
  • divisible_by_3_length_word_length_tuples = tuple(...): This line initializes a variable named divisible_by_3_length_word_length_tuples and assigns it a tuple created by using a generator expression.
    • (... for word in set(sentence.split())): The generator expression iterates through each unique word in the sentence by splitting the sentence into words using split() and converting the result to a set to eliminate duplicate words.
    • (word, len(word)) for ...: For each unique word word, it creates a tuple containing the word itself and its length (number of characters).
    • if len(word) % 3 == 0: The condition if len(word) % 3 == 0 checks if the length of the word is divisible by 3.
  • print(sentence): This line of code prints the original sentence to the console.
  • print(divisible_by_3_length_word_length_tuples): This line of code prints the divisible_by_3_length_word_length_tuples tuple to the console.

Source Code

sentence = "Hello, how are you?"
divisible_by_3_length_word_length_tuples = tuple((word, len(word)) for word in set(sentence.split()) if len(word) % 3 == 0)
 
print(sentence)
print(divisible_by_3_length_word_length_tuples)

Output

Hello, how are you?
(('are', 3), ('how', 3), ('Hello,', 6))

Example Programs