List comprehension

I’m on step 12

Carly thinks she can bring in more customers by advertising all of the haircuts she has that are under 30 dollars.

Use a list comprehension to create a list called cuts_under_30 that has the entry hairstyles[i] for each i for which new_prices[i] is less than 30.

You can use range() in your list comprehension to make i go from 0 to len(new_prices) - 1.

So heres my code:

cuts_under_30 = [i for i in range(len(new_prices)) if i < 30]

Heres the output

[0, 1, 2, 3, 4, 5, 6, 7]

List comprehensions are not my strongest point yet, I dont really understand what the questions saying when it says "… that has the entry hairstyles[i]"

I think I understand what my code is doing, its saying if the index number is <30 then print the index

Im just not sure how to print the actual values that are at each index based on an if statement

you are right, but that is not the desired result

well, the exercise tells you how to? hairstyles[i] use the index (i is often used as an abbreviation for index) to get values from the array

cuts_under_30 = [hairstyles[i] for i in range(len(new_prices)) if i < 30]

this is the best I could come up with?

output still aint right:

['bouffant', 'pixie', 'dreadlocks', 'crew', 'bowl', 'bob', 'mohawk', 'flattop']

you now appending the hairstyles, that is good. But your comparison is off.

you don’t check if the price is less then 30, you check if the index is less then 30

1 Like

cuts_under_30 = [hairstyles[i] for i in range(len(new_prices)) if new_prices[i] < 30]

boom! thank you