Reputation: 45
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.
Upvotes: 0
Views: 302
Reputation: 317
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()
.
Upvotes: 2
Reputation: 7509
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)]
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!
Upvotes: 4