Tuple of pairs of words and their common letters in Python


This Python code processes two words, word1 and word2, and creates a tuple called common_letter_tuples. Each element in this tuple is a pair containing a character that is common to both words. Here's how the code works:

  • word1 = "apple": This line initializes a variable named word1 and assigns it the string "apple."
  • word2 = "cherry": This line initializes a variable named word2 and assigns it the string "cherry."
  • common_letter_tuples = tuple((char, char) for char in word1 if char in word2): This line initializes a variable named common_letter_tuples and assigns it a tuple created using a generator expression.
    • for char in word1: This part of the code sets up a loop that iterates through each character char in the string word1.
    • if char in word2: For each character, it checks if the character is present in the string word2.
    • (char, char): If a character is common to both words, it creates a pair with the character. The pair contains the same character twice.
    • tuple(...): This surrounds the generator expression and converts the generated character pairs into a tuple.
  • print(word1): This line of code prints the original word1 to the console.
  • print(word2): This line of code prints the original word2 to the console.
  • print(common_letter_tuples): This line of code prints the common_letter_tuples tuple (which contains pairs of common characters) to the console.

Source Code

word1 = "apple"
word2 = "cherry"
common_letter_tuples = tuple((char, char) for char in word1 if char in word2)
print(word1)
print(word2)
print(common_letter_tuples)

Output

apple
cherry
(('e', 'e'),)

Example Programs