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

Joshua Senneff
Joshua Senneff
1,159 Points

Help me understand this python code?

Hi, I'm in the python course and I looked up the solution to this code challenge but I don't really understand how this code works. Why is there an i in front of the for and why is the solution to join them instead of removing them??

disemvowel.py
def disemvowel(word):
    return ''.join([i for i in word if not i in 'aeiouAEIOU'])

2 Answers

Greg Kaleka
Greg Kaleka
39,021 Points

That's some fancy Python right there. I'm fairly comfortable with Python, and that's too fancy for me. Here's equivalent code that's easier to understand, imo:

solution.py
def disemvowel(word):
    consonants = []
    for letter in word:
        if not letter in 'aeiouAEIOU':
            consonants.append(letter)
    return ''.join(consonants)

Remember PEP 20:

The Zen of Python, by Tim Peters

Beautiful is better than ugly.

Explicit is better than implicit.

Simple is better than complex.

Complex is better than complicated.

...

Readability counts.

I'm cherry-picking, but still.

Happy coding!

Cheers :beers:

-Greg

Joshua Senneff
Joshua Senneff
1,159 Points

Oh Ok! I think I get what the code does now. It separates them in the for loop and appends them together again right?

Greg Kaleka
Greg Kaleka
39,021 Points

Sorry - I didn't really explain!

  • Creates an empty list called consonants
  • For loop goes through each letter one at a time
    • If the letter is not a vowel, it adds the letter to the list
    • If the letter is a vowel, it does nothing and moves on to the next character in word
  • Finally it takes the list and joins the characters back together into a string (with no delimiter)

So if you ran

disemvowel("Hello Alex!")

the for loop would create a list that looked like this:

['H', 'l', 'l', ' ', 'l', 'x', '!']

and then

''.join(['H', 'l', 'l', ' ', 'l', 'x', '!'])

turns into "Hll lx!", which is returned.

Make sense? Note that even though we called it word and consonants, the function's return will actually include any non-vowel characters like spaces and punctuation. You could get more complicated and only include consonants and even throw an error if spaces are included in word, but this is good for now :blush:

Joshua Senneff
Joshua Senneff
1,159 Points

Oh, Okedoke, thank you so much!