Question about pratice case in practice module - Loops Python

Hi, I have a simple question about one of the quiz questions from the practice module of Loops.

It is related to this code:

greetings = ["aloha", "bonjour", "hello", "hola", "salut"] short_list = [greeting + " is a nice word to greet people." for greeting in greetings if greeting[0] == "a"] print(short_list[0])

To me it seems like it will only print the greeting if the greeting is equal to “a”, but the correct answer is that it prints “aloha is a nice word to greet people.”

It might seem like an uncessesary question, but I want to understand why. So are anyone here able to explain why it prints as intended? Shouldn’t it check if greeting at index 0 is equal to “a” before printing, and then only print the greeting if that is the case?

Thanks in advance for your patience and time.

Hi,
So, in this section, greeting is going to take the value of each of the elements of the list greetings in turn.

[greeting + " is a nice word to greet people." for greeting in greetings if greeting[0] == "a"]

the greeting[0] == “a” is comparing ‘a’ with just the first letter for each word, and if the first letter is ‘a’ it’ll add the whole word along with the rest of the phrase to short_list.
Then, on the next line, short_list[0] is going to be the first entry in that list, which is going to be, “aloha is a nice word to greet people.”

hope that helps

1 Like

Yes!

After your answer I did some simple experimentation.
I tried to remove the == “a” and it printed just the same. But I also see that if I change “aloha” to “bloha”, it doesn’t print and gives me an IndexError. So it makes sense that it is checking for the first letter of index 0. Not sure if I understand why we would add such a check to the code (but I am a beginner, so), or how it knows to check if the string begins with the letter a instead of if the string is “a”. But atleast I understand what happened!

Thanks you for sharing ^^