List comprehensions that use the range function (Python)

My question is pertaining to the Carly’s Clippers project (

Step 12 asks you to create a list comprehension that uses a piece of code that looks like:

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

I’m just curious, why does the range have to be equal to len(new_prices) - 1? Wouldn’t that make the loop stop just short of the full list? Also, is it correct to say that the purpose of using the range function here is just to tell the program how many times to check if new prices is < 30? If that’s true then it makes even less sense to stop the loop short of the full list because then you’d potentially be missing out on a last piece of data.

In this case, it doesn’t matter, as removing the - 1 doesn’t change anything, but I’m confused why they tell you to do that, and then even the hint doesn’t include it.

That’s because the last item in the prices list is not less than 30. The - 1 should not be there, as you deduce.

Something to consider: Since the data is not being mutated, we can use simple read-only membership…

... [x for x in new_prices if x < 30]

Okay, thank you, I think I understand a little bit better now.

1 Like