Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Collections (2016, retired 2019) Lists Disemvowel

What is optimal way of solving disemvowel?

I did complete the disemvowel challenge by using loop (v in vowels) within a loop of (w in word) to iterate, then reconstructed a new word (new_word += w) from characters where w == v did not occur.

Is there a more efficient way?

1 Answer

Manish Giri
Manish Giri
16,266 Points

You could use List Comprehension and the .join() function to first create a list that does not have the vowels, then use .join() to create a string from the list -

def disemvowel(word):
    vowels = ["a", "e", "i", "o", "u"]
    return "".join(w for w in word if w.lower() not in vowels)

If I break it down -

  1. w for w in word basically gives you all the letters in word, because word being a str object is iterable.
  2. the condition if w.lower() not in vowels is a containment check - it checks if the current letter is not a vowel, and if it isn't, it is returned in the list.
  3. The final list is joined to form a string using .join().

very nice. I did not realize that you could write python in this way. Hopefully this approach will be presented in future instructions. Thanks.