Generate a set of words with at least one vowel from a list of words


This Python code uses a set comprehension to create a set named vowel_words, which contains words from the words list that contain at least one vowel (a, e, i, o, or u). Here's how the code works:

  • vowel_words = {word for word in words if any(char.lower() in 'aeiou' for char in word)}: This line initializes the set vowel_words using a set comprehension.
    • for word in words: This part of the code iterates through each word in the words list.
    • if any(char.lower() in 'aeiou' for char in word): It checks if at least one character in the current word is a lowercase vowel (a, e, i, o, or u).
  • print(words): This line of code prints the original list of words, which is ["apple", "banana", "cherry"], to the console.
  • print(vowel_words): This line of code prints the vowel_words set, which contains words with at least one vowel, to the console.

Source Code

words = ["apple", "banana", "cherry", ]
vowel_words = {word for word in words if any(char.lower() in 'aeiou' for char in word)}
print(words)
print(vowel_words)

Output

['apple', 'banana', 'cherry']
{'banana', 'apple', 'cherry'}

Example Programs