Can some help me the list comprehension of the below for loop?

38 views Asked by At

Create a list of all elements in the string “Yellow Yaks like yelling and yawning and #yesturday they yodled while eating yuky yams” by ignoring a,e,i,o,u in the element

I wrote the for loop:

mystring = "Yellow Yaks like yelling and yawning and yesterday they yodled while eating yuky yams"

newlist =[]
mylist=mystring.split()
for word in mylist:
    for letter in ['a','e','i','o','u']:
        if letter in word:
            word =word.replace(letter,'')
    newlist.append(word)
newlist

Output from the for loop:

['Yllw',
 'Yks',
 'lk',
 'yllng',
 'nd',
 'ywnng',
 'nd',
 'ystrdy',
 'thy',
 'ydld',
 'whl',
 'tng',
 'yky',
 'yms']

I tried the following for compressed for loop:

mylist=[word.replace(letter,'') for word in mystring.split() for letter in ['a','e','i','o','u'] if letter in word]
mylist

Output:

['Yllow',
 'Yellw',
 'Yks',
 'lik',
 'lke',
 'ylling',
 'yellng',
 'nd',
 'ywning',
 'yawnng',
 'nd',
 'yesterdy',
 'ystrday',
 'thy',
 'yodld',
 'ydled',
 'whil',
 'whle',
 'eting',
 'ating',
 'eatng',
 'yky',
 'yms']

I know the logic is incorrect but don't know how to fix it. Can you explain what needs to be done to fix it and why?

1

There are 1 answers

1
Nyakwar Dayo On
vowels = 'aeiou'
final_list = [word.translate(str.maketrans('', '', vowels)) for word in mystring.split()]
print(final_list)