Trouble with list comprehension

I have trouble understanding the logic behind the code on line 20.

Here’s the excercise and code:
https://www.codecademy.com/journeys/computer-science/paths/cscj-22-intro-to-programming/tracks/cscj-22-fundamentals-of-python/modules/cscj-22-python-loops/projects/python-carlys-clippers

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

It’s a one line bit of code that produces a new list (rather than defining a function).

#prior code:
hairstyles = ["bouffant", "pixie", "dreadlocks", "crew", "bowl", "bob", "mohawk", "flattop"]
prices = [30, 25, 40, 20, 20, 35, 50, 35]
last_week = [2, 3, 5, 8, 4, 4, 6, 2]

new_prices = [price - 5 for price in prices]
print(new_prices)

#your question:
cuts_under_30 = [hairstyles[i] for i in range(len(prices)) if new_prices[i] < 30] 
#new list = [index of item in hairstyles list for index in prices list *if* the index of the item in new_prices is less than $30]

print(cuts_under_30)

>>['bouffant', 'pixie', 'crew', 'bowl']

You use range(len()) to iterate over items in a list.

See:

And,

This also might be of some help here.

Thanks for your reply!

1 Like