Tuple of tuples with word and its reversed form in Python


This Python code processes the words list and creates a tuple called reversed_tuples. Each element in this tuple is a pair containing a word from the list and its reverse. Here's how the code works:

  • words = ["apple", "banana", "cherry", "date"]: This line initializes a variable named words and assigns it a list containing four words.
  • reversed_tuples = tuple((word, word[::-1]) for word in words): This line initializes a variable named reversed_tuples and assigns it a tuple created using a generator expression.
    • for word in words: This part of the code sets up a loop that iterates through each word word in the words list.
    • (word, word[::-1]): For each word, it creates a pair that consists of the original word and its reverse. The reverse is obtained by using slicing with word[::-1], which reverses the characters in the word.
    • tuple(...): This surrounds the generator expression and converts the generated pairs into a tuple.
  • print(words): This line of code prints the original words list to the console.
  • print(reversed_tuples): This line of code prints the reversed_tuples tuple (which contains pairs of words and their reverses) to the console.

Source Code

words = ["apple", "banana", "cherry", "date"]
reversed_tuples = tuple((word, word[::-1]) for word in words)
print(words)
print(reversed_tuples)

Output

['apple', 'banana', 'cherry', 'date']
(('apple', 'elppa'), ('banana', 'ananab'), ('cherry', 'yrrehc'), ('date', 'etad'))

Example Programs