When to use range(len(list)-1)?

In the Carly’s Clippers exercise in Loops section, Q12 mentions to use range(len(list)-1) to find all haircuts less than $30. The haircuts and their prices are lists.

I’m not able to understand why we need to use range(len(list)-1). Can’t we just use range(len(list))?

These’re the lists used:
hairstyles = ["bouffant", "pixie", "dreadlocks", "crew", "bowl", "bob", "mohawk", "flattop"]

new_prices = [25, 20, 35, 15, 15, 30, 45, 30]

This question has come up many times over the past several years, so you are not alone in wondering what is going on. The only explanation I have ever been able to come up with (pretending to read the author’s mind) is that they want us to know that the last value of a range (the upper bound) is excluded

x = list(range(10))

print (x)

# [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

Notice that ‘10’ is not in the range?

Bottom line,

that is the correct interpretation.

Thanks for the prompt response. I tried running the exercise with range(len(list)-1) and range(len(list)) as well. Both returned the same result which caused me more confusion. I wanted to make sure if I was missing anything.

1 Like

Can you show us your results? They should not be the same.

QUESTION was: 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.

SOLUTION
hairstyles = ["bouffant", "pixie", "dreadlocks", "crew", "bowl", "bob", "mohawk", "flattop"]

new_prices = [25, 20, 35, 15, 15, 30, 45, 30]

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

OR

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

Both return the same result for me.
['bouffant', 'pixie', 'crew', 'bowl']

1 Like

Move the 20 to the end of the prices list (and ‘pixie’ to the end of its list) and run the last example again. Is the ‘pixie’ in the output?

hairstyles = ["bouffant", "dreadlocks", "crew", "bowl", "bob", "mohawk", "flattop", "pixie"]
new_prices = [25, 35, 15, 15, 30, 45, 30, 20]
cuts_under_30 = [hairstyles[i] for i in range(len(new_prices)-1) if new_prices[i] < 30]
print(cuts_under_30)

Output is
['bouffant', 'crew', 'bowl']

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

The output does include “pixie”:
['bouffant', 'crew', 'bowl', 'pixie']

The reason why am confused is because len(list) returns total number of elements in a list.
So if we’ve a list of 10 items, len(list) returns 10.
But range(len(list)) would be (0,9) and range(len(list)-1) will further decrease one element from the list. Isn’t it?

1 Like

Now you’re seeing the correct picture. I hope you understand why pixie didn’t print out when it was (len(…) - 1).

1 Like