I’m having a tough time understanding loops. Specifically when to/not to use range(len()) when creating a loop.
I am working on the Carly’s Clippers project for example.
Carly thinks she can bring in more customers by advertising all of the haircuts she has that are under
Use a list comprehension to create a list called
cuts_under_30that has the entry
new_prices[i]is less than
You can use
range()in your list comprehension to make
len(new_prices) - 1.
Here is my code that throws an index out of range error. Ignore the project instructions to use list comprehension. I’m struggling enough already.
hairstyles = ["bouffant", "pixie", "dreadlocks", "crew", "bowl", "bob", "mohawk", "flattop"] new_prices = [25, 20, 35, 15, 15, 30, 45, 30] cuts_under_30 =  for item in new_prices: if new_prices[item] < 30: cuts_under_30.append(hairstyles[item]) print(cuts_under_30)
However, if I change one of the lines to
for item in range(len(new_prices)):, the code works. Why do I need to use range(len())? Why am I getting index out of range?
In other loops I don’t use range(len()) but don’t get an index error:
prices = [30, 25, 40, 20, 20, 35, 50, 35] total_price = 0 for price in prices: if price > 0: total_price += price