0

If I have a list similar to

mylist = ["danny","florence","micheal","klrv","yrcv"]

And I want to remove the strings that do not have vowels in them and put them in a new list, resulting in me have two lists. How do I do it?

I tried coding it manually

mylist_no_vowel = ["klrv","yrcv"]

Then using .remove to make original list smaller. But I feel there is a code to automate it instead of doing it manually.

1
  • 1
    Don't call your list list, it overrides the builtin list function. :) Commented Dec 11, 2020 at 17:47

2 Answers 2

4

The quick-and-dirty one-liner is:

mylist = ["danny","florence","micheal","klrv","yrcv"]
mylist_no_vowel = [word for word in mylist if not any(character in 'aeiou' for character in word)]

Explanation

The second line uses a syntax called a list comprehension, which is a Python idiom for building a list (in this case, by filtering another list). The code is equivalent to:

mylist = ["danny","florence","micheal","klrv","yrcv"]
mylist_no_vowel = []

for word in mylist:
    if not any(character in 'aeiou' for character in word):
        mylist_no_vowel.append(word)

Translating, we start an empty list called mylist_no_vowel, then we iterate through each word in the original list mylist. For each word, we check if any of their characters is a vowel, using the any function. If that's not the case, we add the word to the mylist_no_vowel list.

Note that I changed your starting list variable name from list to mylist, since list is actually a reserved word in Python - you're overwriting the built-in list function by naming a variable like that!

Sign up to request clarification or add additional context in comments.

3 Comments

Hi, this works absolutely fine, but when i want to use mylist. It still includes those two strings. I'm just going to use the .remove function to get those strings out
Also, i did't know but i have changed it now to mylist
You can create a third list (e.g. mylist_only_vowel) for storing all words with at least one vowel simply by removing the word not from my example. This is probably easier than trying to directly recycle mylist.
2

The following codes should serve the purpose.

mylist = ["danny", "florence", "micheal", "klrv", "yrcv"]

mylist_no_vowel = list(filter(lambda x: set('aeiou') & set(x)==set(), mylist))

print(mylist_no_vowel)

Here is the result, which is the same as your expected result:

['klrv', 'yrcv']

The idea is to use the anonymous function to filter out each element x of mylist that contains vowels via keeping each element x of mylist such that the intersection of set(x) and set('aeiou') is the empty set set().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.