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

i'm really stuck in this challenge

create a variable named y_words that uses a list comprehension to only contain the words from words that start with the letter "y".

here is my code

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

3 Answers

Kristian Gausel
Kristian Gausel
14,661 Points
y_words = [ y for y in words if y[0] == "y"]

The code is pretty self-explanatory. You just missed the condition to be included =)

thank you very much

Chris Grazioli
Chris Grazioli
31,225 Points

Kristian, Nothing against you my friend. It just seemed to me that the persons understanding ( and I could still be wrong) was in question due to the use of "y for y in words if y[0]=='y' " and that going forward that kind of naming convention might still confuse more people.

Kristian Gausel
Kristian Gausel
14,661 Points

The choice of variable name was indeed indicating that. So thanks for clarifying :)

Chris Grazioli
Chris Grazioli
31,225 Points

I don't like it when people use vague names for things, also it sucks for the person new to the challenge trying to understand what is going on TRY THIS

words = [
    'yellow',
    'red',
    'yesterday',
    'tomorrow',
    'maybe',
    'zucchini',
    'eggplant',
    'year',
    'month',
    'yell',
    'yonder',
    'today',
]
#This might make more sense to some
y_words= [word for word in words if word[0]=='y']

Explained left to right: Its essentially saying "y_words" is a list comprehension where it appends the current "word" being considered from "word" in "words" (Which is just another way of saying the nth item in the list ) "if" the first letter in the word currently being considered is a letter y "word[0]=='y' "

Explain another way: You can break the Comprehension into a few parts:

=[what it will add to the list + for + a thing + in + a list of things + if some condition the thing meets]

=[word + for + word + in+ words + word[0]=='y' ]

Kristian Gausel
Kristian Gausel
14,661 Points

His only question was how to add the if statement. Otherwise I would hae explained

Chufan Xiao
Chufan Xiao
18,955 Points

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