Pairs of distinct words and their reversed forms in a sentence as a tuple in Python


This Python code processes a sentence, sentence, and creates a tuple named distinct_reversed_word_tuples. The tuple contains pairs of words from the sentence, with one element being the original word and the other element being the reversed version of the word. Here's how the code works:

  • sentence = "Hello, how are you?": This line initializes a variable named sentence and assigns it the given sentence.
  • distinct_reversed_word_tuples = tuple((word, word[::-1]) for word in set(sentence.split())): This line initializes a variable named distinct_reversed_word_tuples and assigns it a tuple created using a generator expression.
    • for word in set(sentence.split()): This part of the code sets up a loop that iterates through each distinct word word in the sentence after splitting it by spaces using sentence.split(). The set() function is used to ensure that only distinct words are considered.
    • (word, word[::-1]): For each word, a tuple is created containing the original word and its reverse obtained by slicing it with word[::-1].
    • tuple(...): This surrounds the generator expression and converts the generated pairs into a tuple.
  • print(sentence): This line of code prints the original sentence to the console.
  • print(distinct_reversed_word_tuples): This line of code prints the distinct_reversed_word_tuples tuple to the console.

Source Code

sentence = "Hello, how are you?"
distinct_reversed_word_tuples = tuple((word, word[::-1]) for word in set(sentence.split()))
print(sentence)
print(distinct_reversed_word_tuples)

Output

Hello, how are you?
(('you?', '?uoy'), ('are', 'era'), ('how', 'woh'), ('Hello,', ',olleH'))

Example Programs