Tuple of common letters between two words in Python


This Python code creates a tuple called common_letters, which contains the characters that are common between the two words, word1 and word2. Here's how the code works:

  • word1 = "apple": This line initializes a variable named word1 and assigns it the string "apple."
  • word2 = "banana": This line initializes a variable named word2 and assigns it the string "banana."
  • common_letters = tuple(char for char in word1 if char in word2) : This line of code 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 word1.
    • if char in word2: For each character in word1, it checks if the character is also present in word2.
    • char: If a character is found in both word1 and word2, it is included in the generator expression.
    • tuple(...): This surrounds the generator expression and converts the generated common characters 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 the two words) to the console.

Source Code

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

Output

apple
banana
('a',)

Example Programs