[Solved] How can you remove the vowels in a function using a list comprehension?


There are a number of problems with your code, specifically this line:

list2 = [list2[n] = list2[n].replace(vowel, "") for n in range(len(list2)) if n in vowels]
  • you can not assign = within a list comprehension, just remove the list2[n] = part
  • vowel is not defined, you should probably execute this in a loop for vowel in vowels
  • the check if n in vowels does not make sense; n is an int, whereas vowels is a list of str

To keep close to your approach, you can try this:

def novowelsort(the_list):
    vowels = ["a", "e", "i", "o", "u"]
    list2 = the_list
    for v in vowels:
        list2 = [list2[n].replace(v, "") for n in range(len(list2))]
    return list2

Or using a regular expression to replace all vowels at once:

import re
def novowelsort(the_list):
    return [re.sub(r"[aeiou]", "", x) for x in the_list]

However, note that none of those actually sorts anything, as the name of the function implies.

solved How can you remove the vowels in a function using a list comprehension?