Create a list of lowercase vowels from a string


This Python code takes a string and creates a new list called vowels using a list comprehension. The new list contains all the vowels (both lowercase and uppercase) from the original string. Here's how the code works:

  • string = "Hello, world!": This line initializes a variable named string and assigns it a string containing the text "Hello, world!"
  • vowels = [char for char in string if char.lower() in 'aeiou']: This line of code initializes a variable named vowels and assigns it the result of a list comprehension.
    • for char in string: This part sets up a loop that iterates through each character char in the string.
    • char.lower() in 'aeiou': For each character in the string, this expression first converts the character to lowercase using the lower() method to ensure case insensitivity. It then checks if the lowercase character is in the string 'aeiou', which contains all lowercase vowels.
    • [char for char in string if char.lower() in 'aeiou']: This is the list comprehension itself. It iterates through the characters in the string, checks if each character is a lowercase vowel, and includes the vowels in the new list.
  • print(string): This line of code prints the original string to the console.
  • print(vowels): This line of code prints the vowels list to the console.

Source Code

string = "Hello, world!"
vowels = [char for char in string if char.lower() in 'aeiou']
print(string)
print(vowels)

Output

Hello, world!
['e', 'o', 'o']

Example Programs