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 Functional Python Functional Workhorses Filter comprehension

Neil Gordon
Neil Gordon
8,823 Points

looking for assistance with list comprehension in Python. How do you take out only words that start with 'y'

y_words = [word for word in words if startsWith('y'), words]
filters.py
words = [
    'yellow',
    'red',
    'yesterday',
    'tomorrow',
    'zucchini',
    'eggplant',
    'year',
    'month',
    'yell',
    'yonder',
]

y_words = [word for word in words if startsWith('y'), words]

2 Answers

The way you would check if the first letter is 'y' is by checking if its index 0 is y. This can be done by using the condition if word[0] == 'y'. Also, words is not required after the end of your list comprehension. Your list comprehension should look like this:

y_words = [word for word in words if word[0]=='y']

If you have any further questions please feel free to leave a comment :)

Thanks,

Haider

Neil Gordon
Neil Gordon
8,823 Points

Thank you Haider Ali the index zero makes so much sense

gustavoalvarado
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
gustavoalvarado
Python Development Techdegree Graduate 11,933 Points

Hi! Here is another option to solve the Challenge. Have a nice day!

words = [
    'yellow',
    'red',
    'yesterday',
    'tomorrow',
    'maybe',
    'zucchini',
    'eggplant',
    'year',
    'month',
    'yell',
    'yonder',
    'today',
]

y_words = [words for words in words if words.startswith('y')]