Create a list of characters that are not vowels from a string


This Python code takes a string and creates a new list called non_vowels, which contains all the characters from the original string that are not vowels (both lowercase and uppercase vowels are considered). Here's how the code works:

  • string = "Hello, world!": This line initializes a variable named string and assigns it a string containing a sentence.
  • non_vowels = [char for char in string if char.lower() not in 'aeiou']: This line of code initializes a variable named non_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() not in 'aeiou': For each character in the string, 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 string if char.lower() not in 'aeiou']: This is the list comprehension itself. It iterates through the characters in the string, includes only the characters that are not vowels (both lowercase and uppercase) in the new list.
  • print(string): This line of code prints the original string to the console.
  • print(non_vowels) : This line of code prints the non_vowels list (which contains the characters that are not vowels) to the console.

Source Code

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

Output

Hello, world!
['H', 'l', 'l', ',', ' ', 'w', 'r', 'l', 'd', '!']

Example Programs