Tuple of distinct vowels and consonants from a list of words in Python


This Python code processes the words list and creates two tuples: vowels and consonants. The vowels tuple contains all the vowels from the words in the list, and the consonants tuple contains all the consonants. 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.
  • vowels = tuple(char for word in words for char in word if char.lower() in 'aeiou'): This line initializes a variable named vowels and assigns it a tuple created using a generator expression.
    • for word in words: This part of the code sets up a nested loop that iterates through each word word in the words list.
    • for char in word: For each word, it sets up another nested loop that iterates through each character char in the word.
    • if char.lower() in 'aeiou': For each character, it checks if the character (converted to lowercase) is a vowel (i.e., if it's in the string 'aeiou'). If it's a vowel, it includes the character in the generator expression.
    • tuple(...): This surrounds the generator expression and converts the generated vowel characters into a tuple.
  • consonants = tuple(char for word in words for char in word if char.lower() not in 'aeiou'): This line initializes a variable named consonants and assigns it a tuple created using a generator expression.
    • for word in words: This part of the code sets up a nested loop that iterates through each word word in the words list.
    • for char in word: For each word, it sets up another nested loop that iterates through each character char in the word.
    • if char.lower() not in 'aeiou': For each character, it checks if the character (converted to lowercase) is not a vowel (i.e., if it's not in the string 'aeiou'). If it's a consonant, it includes the character in the generator expression.
    • tuple(...): This surrounds the generator expression and converts the generated consonant characters into a tuple.
  • print(words): This line of code prints the original words list to the console.
  • print(vowels): This line of code prints the vowels tuple (which contains all the vowel characters) to the console.
  • print(consonants): This line of code prints the consonants tuple (which contains all the consonant characters) to the console.

Source Code

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

Output

['apple', 'banana', 'cherry', 'date']
('a', 'e', 'a', 'a', 'a', 'e', 'a', 'e')
('p', 'p', 'l', 'b', 'n', 'n', 'c', 'h', 'r', 'r', 'y', 'd', 't')

Example Programs