Tuple of distinct vowels in a list of words in Python


This Python code creates a tuple called distinct_vowels, which contains all the distinct lowercase vowel characters from the words in the words list. 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.
  • distinct_vowels = tuple(char.lower() for word in words for char in word if char.lower() in 'aeiou'): This line of code initializes a variable named distinct_vowels and assigns it a tuple created using a generator expression.
    • for word in words: This part of the code sets up the outermost loop that iterates through each word word in the words list.
    • for char in word: Within the outer loop, it sets up a nested loop that iterates through each character char in the current word.
    • if char.lower() in 'aeiou': For each character in each word, it checks if the lowercase version of char is in the string 'aeiou', effectively identifying lowercase vowels.
    • char.lower(): If a lowercase vowel character is found, it includes it in the generator expression.
    • tuple(...): This surrounds the generator expression and converts the generated lowercase vowel characters into a tuple.
  • print(words): This line of code prints the original words list to the console.
  • print(distinct_vowels): This line of code prints the distinct_vowels tuple (which contains the distinct lowercase vowel characters from the words) to the console.

Source Code

words = ["apple", "banana", "cherry", "date"]
distinct_vowels = tuple(char.lower() for word in words for char in word if char.lower() in 'aeiou')
print(words)
print(distinct_vowels)

Output

['apple', 'banana', 'cherry', 'date']
('a', 'e', 'a', 'a', 'a', 'e', 'a', 'e')

Example Programs