Something in that boggles me is why range(a, b) in Python includes the a value, but not b. In math, range(a, b) implies neither a nor b are included – the parentheses are exclusive. Square brackets – range[a, b] – are inclusive. So why is Python’s range(a, b) part inclusive, part exclusive? It doesn’t follow the math rules I’d expect.
I did some research and came across this snippet:
Python range is inclusive because it starts with the first argument of the range() method, but it does not end with the second argument of the range() method; it ends with the end – 1 index. The reason is zero-based indexing.
https://appdividend.com/2021/03/24/python-range-inclusive/
Now I have a lead, but still want to understand: How does zero-based indexing affect range inclusion? Here’s an explanation that made things *click* for me.
I think it may help to add some simple ‘real life’ reasoning as to why it works this way, which I have found useful when introducing the subject to young newcomers:
With something like ‘range(1,10)’ confusion can arise from thinking that pair of parameters represents the “start and end”.
It is actually start and “stop”.
Now, if it were the “end” value then, yes, you might expect that number would be included as the final entry in the sequence. But it is not the “end”.
Others mistakenly call that parameter “count” because if you only ever use ‘range(n)’ then it does, of course, iterate ‘n’ times. This logic breaks down when you add the start parameter.
So the key point is to remember its name: “stop“. That means it is the point at which, when reached, iteration will stop immediately. Not after that point.
So, while “start” does indeed represent the first value to be included, on reaching the “stop” value it ‘breaks’ rather than continuing to process ‘that one as well’ before stopping.
One analogy that I have used in explaining this to kids is that, ironically, it is better behaved than kids! It doesn’t stop after it supposed to – it stops immediately without finishing what it was doing. (They get this 😉 )
Another analogy – when you drive a car you don’t pass a stop/yield/’give way’ sign and end up with it sitting somewhere next to, or behind, your car. Technically you still haven’t reached it when you do stop. It is not included in the ‘things you passed on your journey’.
User dingles – https://stackoverflow.com/questions/4504662/why-does-rangestart-end-not-include-end
It makes more sense now. Python’s range(a, b) starts iterating at a and stops at b – right when it hits b, so that it does not include it.
Onward with learning, kids!










