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 trialJoshua Senneff
1,159 PointsHelp 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??
def disemvowel(word):
return ''.join([i for i in word if not i in 'aeiouAEIOU'])
2 Answers
Greg Kaleka
39,021 PointsThat'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:
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
-Greg
Joshua Senneff
1,159 PointsOh, Okedoke, thank you so much!
Joshua Senneff
1,159 PointsJoshua Senneff
1,159 PointsOh 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
39,021 PointsGreg Kaleka
39,021 PointsSorry - I didn't really explain!
word
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