Python: for i in range (1, 10), print (i). Why does it not print the number 10?

Question

I talked with my data science tutor for almost 20 minutes and he couldn't give me an answer beyond: "It just doesn't give you the last value. It's just something you remember."

Posted Oct 29, 2021, 10:17 PM UTC

26
vanndrake•

First arg is including. Srcond one is excluding

3
BeastOfOneOP•

So it's range from (and including) 1 up to (but not including) 10?

2
vanndrake•

Correct

5
proka_ro•

Because python...

1
[deleted]•

Which language doesn't do that?

Programmers are used to index 0, and calling range(0, 10) is equivalent of writing a common for-loop for (int i = 0; i < 10; i++).

2
Suspicious-Service•

Here is a stack overflow question, might help you know what too google if you're still confused https://stackoverflow.com/questions/11364533/why-are-slice-and-range-upper-bound-exclusive

There are a few reasons I understand:

  1. If your starting index is 0, the upper bound is the same as number of elements (if they're ints) so that's nice

  2. Cutting up consecutive sections is nice, since the upper bound of 1st slice is the beginning index of the next

  3. It doesn't really matter, some languages are upper bound inclusive. Someone just chose thus convention and it's kept for consistency

1