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
30
dollars.
Use a list comprehension to create a list calledcuts_under_30
that has the entryhairstyles[i]
for eachi
for whichnew_prices[i]
is less than30
.
You can userange()
in your list comprehension to makei
go from0
tolen(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