Question related to length of lists

My question is related to how a snippet of code from the video walkthrough of the exercise here differs from my code, but I still get the desired result.

My snippet:

for i in range(len(hairstyles)):
_ total_revenue += (prices[i] * last_week[i])
print(“Total Revenue: $” + str(total_revenue))

Snippet from video walkthrough:

for i in range(0, len(hairstyles) - 1):
_ total_revenue += (prices[i] * last_week[i])
print(“Total Revenue: $” + str(total_revenue))

Question: What is the need to use range(0, len(hairstyles) - 1) vs. my range(len(hairstyles))? I thought range always started at index 0 by default and there is no need to specify the 0. However, if it’s essentially the same code written in a different format (more explicit), why does that -1 return the same answer as mine when I didn’t include it?

That is all we need to iterate a list. A range does not include the uppermost value, so,

range(10)   =>  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

So if

hairstyles = [“bouffant”, “pixie”, “dreadlocks”, “crew”, “bowl”, “bob”, “mohawk”, “flattop”]

range(len(hairstyles)) would be equivalent to range(8) which is [0, 1, 2, 3, 4, 5, 6, 7], correct?

Then wouldn’t range(0, len(hairstyles) - 1): equate to range(7) which is [0, 1, 2, 3, 4, 5, 6]? So is the solution to the exercise provided in the video walkthrough incorrect since we need to be including every hairstyle in the list above?

The for loop in the video is as follows …


There are 8 items in each of the two lists, therefore the final index in each is 7. An appropriate range for the loop would have 7 a its highest value. However, subtracting 1 from the length gives us 7 as the upper limit of the range, which is exclusive, meaning that the index we visit in the final iteration of the for loop is 6. Therefore, the video is incorrect.

The 0 as the lower limit of the range by the way, is indeed the default, so it can be omitted.


Not just the video, the instruction text…

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

This same faux pas occurred in the free track, is_prime exercise. The author is expressing what the range will literally be, which just confuses the situation even more. We should not need to be reminded that range excludes the last value.


Thank you both for your assistance. It is greatly appreciated!