Unique words in a sentence as a tuple in Python


This Python code processes a sentence, sentence, and creates a tuple named unique_words_tuple that contains the unique words from the sentence. Here's how the code works:

  • sentence = "This is a sample sentence with repeated words is": This line initializes a variable named sentence and assigns it the given sentence.
  • unique_words_tuple = tuple(set(sentence.split())): This line initializes a variable named unique_words_tuple and assigns it a tuple containing the unique words from the sentence.
    • sentence.split(): This part of the code splits the sentence into a list of words using whitespace as the separator.
    • set(...): This converts the list of words into a set. Sets in Python only store unique elements, so this operation effectively removes any duplicate words.
    • tuple(...): This surrounds the set and converts it back into a tuple.
  • print(sentence): This line of code prints the original sentence, sentence, to the console.
  • print(unique_words_tuple): This line of code prints the unique_words_tuple tuple (which contains unique words from the sentence) to the console.

Source Code

sentence = "This is a sample sentence with repeated words is"
unique_words_tuple = tuple(set(sentence.split()))
print(sentence)
print(unique_words_tuple)

Output

This is a sample sentence with repeated words is
('This', 'with', 'sample', 'a', 'words', 'sentence', 'repeated', 'is')

Example Programs