List of characters that are vowels or consonants


This Python code takes a list of characters and separates them into two lists: one containing vowels and the other containing consonants. Here's how the code works:

  • characters = ['a', 'b', 'c', 'e', 'f', 'i', 'o'] : This line initializes a variable named characters and assigns it a list containing several characters, including both vowels and consonants.
  • vowels = [char for char in characters 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 characters: This part sets up a loop that iterates through each character char in the characters list.
    • char.lower() in 'aeiou': For each character in the list, this expression converts char to lowercase using char.lower() to ensure case insensitivity and checks if the lowercase character is in the string 'aeiou', which contains all lowercase vowels.
    • [char for char in characters if char.lower() in 'aeiou']: This is the list comprehension itself. It iterates through the characters in the characters list, includes only the characters that are vowels in the new list.
  • consonants = [char for char in characters if char.lower() not in 'aeiou']: This line of code initializes a variable named consonants and assigns it the result of a list comprehension.
    • for char in characters: This part sets up a loop that iterates through each character char in the characters list.
    • char.lower() not in 'aeiou': For each character in the list, this expression converts char to lowercase using char.lower() to ensure case insensitivity and checks if the lowercase character is not in the string 'aeiou', which contains all lowercase vowels.
    • [char for char in characters if char.lower() not in 'aeiou']: This is the list comprehension itself. It iterates through the characters in the characters list, includes only the characters that are not vowels in the new list.
  • print(characters): This line of code prints the original characters list to the console.
  • print(vowels): This line of code prints the vowels list (which contains the vowels) to the console.
  • print(consonants): This line of code prints the consonants list (which contains the consonants) to the console.

Source Code

characters = ['a', 'b', 'c', 'e', 'f', 'i', 'o']
vowels = [char for char in characters if char.lower() in 'aeiou']
consonants = [char for char in characters if char.lower() not in 'aeiou']
print(characters)
print(vowels)
print(consonants)

Output

['a', 'b', 'c', 'e', 'f', 'i', 'o']
['a', 'e', 'i', 'o']
['b', 'c', 'f']

Example Programs