r/learnpython • • Jan 02 '23

Why doesn't python fix the "off by one" in ranges?

I understand that the range function in Python is "off by one" in the sense that range(1,10) generates 1-9 rather than the perhaps reasonably expected 1-10.

My question is: wouldn't it make sense to "fix" this in the language? Or maybe I should say, wouldn't it have made sense in the early days when the language was being created?

1 Upvotes

45 comments sorted by

22

u/[deleted] Jan 02 '23

Probably the most common way to use range() is to do something x amount of times. So if you say

for i in range(10):
    do_stuff()

you want to do_stuff() ten times. That would be lost if it included the 10 and did stuff eleven times— unless it started at 1 instead of 0, which would be a whole other problem

2

u/WyrdByWord Jan 02 '23

I guess that was kind of my question: what would the "whole other problem" have been? I mean, it seems to me (keep in mind, I am very new to this stuff :) that this is a design choice, since some languages do start at 1, and I was curious why something that is at least initially unintuitive to many (thus the many explanations in the beginner resources I have been using) was left that way in what seems a language very geared towards a kind of intuitive design.

3

u/[deleted] Jan 03 '23

Because in the world of computing (which has its roots based in mathematics) you’ll always start with nothing (being 0) and then go up or down from there. For example on a number line with an x and y or even a z axis, you’ll always start at a center point of zero. Zero is too far ingrained in computing, you’ll never likely see the standard across languages change. You just need to train your brain to think differently.

1

u/WyrdByWord Jan 03 '23

I'm certainly in training. I like the starting with nothing rather than something. Very Aristotelian :)

2

u/[deleted] Jan 03 '23

Well arrays with n entries are indexed from 0 to n-1, so e.g. if you do something like

For i in range(len(myArray))
    myArray[i] = myArray[i] + 1

This would now skip the first entry which is the "whole other problem", but it would also run out of the array bounds on the other end, which is bad as well

1

u/[deleted] Jan 03 '23

Our number system is base 10, but the digits only go up to 9. You can make ten possible values from one digit because you start at 0. This doesn't seem like a big difference: giving up the 0 would only be giving up 10% of your possibilities.

But then imagine you're counting in binary: giving up the 0 is giving up half! With more bits it's not as bad, but still. You want two bits to give four possibilities, not three. You want three bits to give eight possibilities, not seven.

So for the math/counting reasons, and for memory address reasons, it makes a lot of sense to start at 0. Now Python could have decided to hide that away under a layer of 1-indexed counting, but that would have alienated people who had seen another language first.

14

u/FuckingRantMonday Jan 02 '23

It's absolutely not broken!

Edit: To elaborate a bit...there are a couple of nice properties that are true under the current implementation:

len(range(a, b)) == b-a        # for a <= b

and

range(a, b) + range(b, c) == range(a, c)        # for a <= b <= c

4

u/WyrdByWord Jan 02 '23

Thanks, all. Please keep in mind that I put "fix" in quotes for a reason: I don't have enough knowledge to call something broken, I just keep coming across resources that explain an apparently often misunderstood behavior and was curious :)

39

u/carcigenicate Carcigenicate Jan 02 '23

I think they made the right choice in terms of consistency with how it works everywhere else. In most languages, end bounds tend to be exclusive. I've always assumed this was a consequence of 0-based indexing being so standard.

If they made range end bounds inclusive, either range(5) for example would have 6 elements instead of 5, or would start at 1 instead of 0. Both issues re-introduce off-by-one errors, so I don't think that would help anything.

-26

u/FutureIntelligenceC3 Jan 02 '23

I think they made the right choice in terms of consistency with how it works everywhere else.

I think what makes Python so great and accessibility is the simplicity and intuitive way to use it. "I want numbers from 1 to 10, therefore i use "range(1,10)" would've made a lot of sense. And generally keeping things because "it has always been that way" is usually not the best argument.

17

u/[deleted] Jan 02 '23

It's actually a pretty good argument considering how much code would break if the next version of Python "fixed" this issue.

7

u/WyrdByWord Jan 02 '23

Oh yeah, I wasn't in any way proposing this should be changed now!

4

u/FutureIntelligenceC3 Jan 02 '23

I think they made the right choice

would've made a lot of sense

The topic of this line of comments was obviously initial design decisions. Not changes that need to be made now. Of course there is no way to "fix" this now.

16

u/carcigenicate Carcigenicate Jan 02 '23

I don't think range(5) having 6 elements or starting at 1 is at all intuitive though. Both ways have their own brand of potential issues, so I think falling back to what's standard is appropriate.

3

u/WyrdByWord Jan 02 '23

Interesting. Perhaps it's my non-math, non-programming, background that makes range(5) meaning 1-5 -- starting at 1 -- seems more intuitive, since that's how most of us learn to count. I see there are some language that have made the choice to start at 1, so understand intuitiveness is always subjective!

3

u/FutureIntelligenceC3 Jan 02 '23

I don't think range(5) [...] starting at 1 is at all intuitive though.

How is that not intuitive? For everyone starting with programming, the first thing they have to learn is that things start counting with 0. Because everywhere else you start with 1. That's the definition of being counter-intuitive.

4

u/carcigenicate Carcigenicate Jan 03 '23

I guess what I consider to be intuitive is colored by my experience, so it isn't a good measure here.

I wrote my last two replies under the assumption 0-based indexing would still be used. If the question is actually "why didn't Python adopt 1-based indexing", then I don't know. They may have decided consistency with the norm was more important.

I personally find it hard to argue either way when I've only used 0-based indexing for a decade.

1

u/[deleted] Jan 03 '23

Unfortunately, you don't know what you're talking about.

2

u/[deleted] Jan 03 '23

If you don't like it, just write your own function that does it the "right" way 🤓🐍🐼

1

u/WyrdByWord Jan 03 '23

Well, I don't dislike it at all, much less enough to try this. I was asking out of sheer curiosity!

2

u/throwaway0891245 Jan 03 '23

I always enjoy when this sort of indexing stuff gets discussed, because there is actually a very famous computer scientist that commented on just this.

Djikstra on why ranges should include the start number and exclude the end number: https://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html

2

u/WyrdByWord Jan 03 '23

That kind of seals the deal :)

1

u/InjAnnuity_1 Jan 03 '23

Another advantage with Djikstra's zero-first approach: a subscript is equal to the distance (in # of list elements) from the start of the list. So you can apply everyday distance logic to your subscripts.

Or, if you like analogies, the first number on the number line is zero. As shown on many (but not all) rulers and tape measures.

2

u/[deleted] Jan 03 '23 edited Jan 04 '23

There is nothing to fix. This is a deliberate design choice. I wouldn't even call it a "design choice" because it's more like a basic tenet of computing.

Count from 0 for i times is equivalent to calling range(i) or range(0, i) or traversing an array to reach the element at array[i].

Why do we begin counting at 0? Because 0000 0000 is a valid binary number, and it would be ridiculous not to use it to index an array just because it's confusing to us. It's not confusing to the computer.

Here's another point. In Python, running a binary search with middle index m is as simple as calling sequence[:m], sequence[m:]. This is a result of the design decision to use the very typical [0..i) indexing system.

2

u/WyrdByWord Jan 03 '23

Thanks! Very helpful. I wonder what the reasoning is in not starting with 0 in some of those other languages. Sounds like a possible mistake on their part :)

7

u/cybervegan Jan 02 '23

The majority of modern programming languages base indexes at zero, otherwise the maths for calculating element addresses has to contain unnecessary subtractions which slow accessing elements down. Modern CPUs use zero-based indexing, and using 1 based indexing means that you have to code to adjust for that.

4

u/PhilipYip Jan 03 '23

Its a deliberate design choice. The following is a quote from the Fluent Python:

The Pythonic convention of excluding the last item in slices and ranges works well with the zero-based indexing used in Python, C, and many other languages. Some convenient features of the convention are:

It’s easy to see the length of a slice or range when only the stop position is given: range(3) and my_list[:3] both produce three items.

It’s easy to compute the length of a slice or range when start and stop are given: just subtract stop - start.

It’s easy to split a sequence in two parts at any index x, without overlapping: simply get my_list[:x] and my_list[x:]

3

u/[deleted] Jan 03 '23

Because it’s not broken. The behavior is correct and documented and consistent with other languages and with fundamental computer science.

2

u/1544756405 Jan 03 '23

There are two design issues that resulted in this.

The first, is whether list (and other ) indexes are going to start at 0 or 1. There are arguments either way, but for python the decision was made to go with zero-based indexing. This is consistent with many other programming languages, so it is not totally off the wall.

Once that decision has been made, then it makes sense for the range() function to be inclusive at the starting end and non-inclusive at the ending range. This means that range(5) will have 5 elements, as expected.

There are others explanations all over the web if you search for "half open intervals programming." The issue is far from being a Python issue; many modern programming languages treat indexing this way.

2

u/voice-of-hermes Jan 03 '23

The behavior of range() is consistent with the indexing of sequences. For example, you can write:

for i in range(len(my_list)):
    do_something_with(my_list[i])

and expect it to work unless you've got some very bizarre shit happening in your program (e.g. a custom type for my_list that doesn't conform to the general contract of sequence types, or some kind of concurrent modification of the object...). Yes, normally you could iterate over the container itself, but there are cases where you wouldn't want to, like in some kind of custom zip() type function, or if skipping some elements, etc. This very condensed and simplistic example is illustrating the principle that consistency in the standard library and language data model is important.

If you really wanted to you could implement your own range and define or import it over the builtin one. But it might be better to learn to "When in Rome..." because you're going to get yourself used to something very inconsistent with how (almost?) all other Python developers do things. So if ever you look at other people's code or they look at yours, there's going to be a world of headaches and pain.

2

u/TheRNGuy Jan 04 '23

It would make old programs not work.

Though I had to fix print and zip from Python 2 to 3, so it's ok.

1

u/Apprehensive_Rice_70 May 16 '25

Yesterday, this came up for me, I was trying to explain C++ access specifiers. But my domain problem is Python, although its a very similar point, language and the meaning we attach matters, as does how quickly we can establish conventions for robust creation of great tools.

My pain with range end being off-by-one, is that I continuously have to write `for index in range(1,num_computers+1):`

and the +1 jars me, everywhere in my code is this +1 now. Everywhere! Anyone came up with a way to, in a syntactically obvious way, produce a collection object/iterators for things. In a way that still produces code that the mostly C++ coders in my team will not struggle to grok?

1

u/ssingal05 Jan 02 '23 edited Jan 02 '23

I personally prefer the current design choice, but that isn't to say that an additional range function wouldn't also be useful for your type of use case.

I think it would be especially useful when combining multiple ranges together. For example, slicing arrays follows the same pattern - arr[0:10] gets the first 10 elements (so not the element in index 10). Getting the next 10 elements is arr[10:20] as opposed to arr[11:20].

Perhaps you don't care about those types of use cases (or the other examples in the comments here), but the language designers have to make choices at every step that everyone may not agree with, so they need to pick what they think most people would like.

Also they can't change the behavior retroactively because it'll affect backwards compatibility.

So tl;dr - design choices like these are opinion based. It is YOUR opinion that it's broken now, but not everyone elses. That being said, I am not against another additional range function in the standard library that handles your use case, because there are other people do share the same opinion as you.

1

u/billsil Jan 03 '23

I don't want it that way, so no please don't fix the language because you'd break every other program. Python's range is great.

You would break range(len(x)) where the length of x is 10. That's a very common pattern.

0

u/chasrmartin Jan 03 '23

Would break infinite other code. Better to just learn that range(1,10) is [1,2,3,4,5,6,7,8,9]

0

u/[deleted] Jan 02 '23

[deleted]

0

u/WyrdByWord Jan 02 '23

Intended, I know. Thus the scare-quotes around "fix." However, the fact that "computers start indexing at 0" wouldn't preclude a language from choosing not to follow that in its implementation, would it?

2

u/InjAnnuity_1 Jan 03 '23

wouldn't preclude a language from choosing not to follow that in its implementation

That's right. In fact, Fortran originally started at 1. As a result, its spinoff, BASIC, followed suit. So does Lua.

There is, of course, a tiny bit of computer overhead for doing so. The bigger overhead, by far, is in the programmer's noggin, when they have to debug their subscript arithmetic (which can be quite prevalent in these older languages) and find that they're off-by-one. Half the time, we end up adjusting by 1 in the wrong direction, before we get it right. Starting at zero tends to eliminate that whole mess.

It should not surprise you, then, that for several decades, Fortran and BASIC have allowed you to start your arrays at other values (usually zero). (For BASIC, see the OPTION BASE statement, to set a program-wide default.)

I fondly remember (circa 1975) defining an array starting at ... 1975. It contained another array, which used subscripts 1 thru 12. (If those had had sub-arrays, they might have used subscripts 1 thru 31.) But that was a very niche case. Most lists have nothing to do with dates or other arbitrary starting points.

You could create your own list-like class in Python, to start whereever you want. However, you would likely have great difficulty using it with code from the standard library, let alone third-party code, which all expect subscripts to start at zero.

The majority of my Python code uses for value in container, so it doesn't even need subscripts to work.

1

u/WyrdByWord Jan 04 '23

Fascinating...thank you for the history and explanation. I do remember doing some Basic in 1983 or so on a TI-99-4A, but not to enough level of detail.

3

u/FuckingRantMonday Jan 02 '23

Not at all! Lua, for instance, starts indexing at 1. I don't like it personally, but Lua obviously exists and is quite popular.

1

u/barkazinthrope Jan 03 '23

Except that experienced programmers everywhere would go WTF???

-11

u/FutureIntelligenceC3 Jan 02 '23

Maybe that's why op wrote "fix"...

0

u/[deleted] Jan 02 '23

[deleted]

-3

u/FutureIntelligenceC3 Jan 02 '23

Was I somehow unclear about how it doesn’t need fixing because it isn’t broken?

My point was that that's exactly what op is saying. So why repeat the obvious???

0

u/[deleted] Jan 03 '23

[deleted]

-1

u/FutureIntelligenceC3 Jan 03 '23

Because the whole idea is flawed.

That was not the point. Of course there are good reasons for it. That's basically what op asked for. But instead of arguing that it'd be bad for performance as you're doing it right now, you just repeated the obvious.