Tuple of common letters between words of different lengths in Python


This Python code processes two words, word1 and word2, and creates a tuple called common_letters. The common_letters tuple contains the characters that are 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_letters = tuple(char for char in word1 if char in word2) : This line initializes a variable named common_letters 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.
    • tuple(...): This surrounds the generator expression and converts the characters that are common to both words 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_letters): This line of code prints the common_letters tuple (which contains the common characters between word1 and word2) to the console.

Source Code

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

Output

apple
cherry
('e',)

Example Programs