-3

The range(1, 11) function acts strangely from a non-programmer's point of view - it does not return the last specified number (11 in this example):

>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  1. Is there any way we can change the way this function works so that it returns a result that includes the last value? Let's say, write a petition to Python developers?

  2. Do you think it makes sense to change the way this function works or leave as it is?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Comrade Che
  • 619
  • 8
  • 25
  • 2
    *"write a petition to Python developers"* Definitely **not** Or **YOU** will have to fix every python programs that use `range()` – Cid Dec 08 '21 at 11:09
  • 2
    There is certainly a way of suggesting changes to the Python-language (https://devguide.python.org/langchanges/), but since range() is such a basic function, I doubt that anyone would have much luck suggesting such a change. Also, and I'm being a little pragmatic here, since Python is used for programming, why would it be important what a non-programmer thinks? And who are we to judge what a non-programmer thinks in the first place? – eandklahn Dec 08 '21 at 11:09
  • 2
    If you want to include the last number, well, you can do `range(1, 11 + 1)` – Cid Dec 08 '21 at 11:09
  • 1
    I propose to close this as duplicate of https://stackoverflow.com/questions/4504662/why-does-rangestart-end-not-include-end, if not as opinion-based. – mkrieger1 Dec 08 '21 at 11:14
  • 1
    Clearly it does not make sense to change it, for reasons described above. At the end of the day, you should just remember that the returned range is `[start, end)` and live with it. If you need `[start, end]`, just pass `end+1` For example, from a non programmer background, originally I found weird that the first element of an array/list has index 0, I got used to it. – nikeros Dec 08 '21 at 11:14
  • You have the same with indexing where `"Hello"[:4]` gives you Hell (pun intended). But that allows us to use `"Hello"[:n] + "Hello"[n:]` for any given `n` and get the full string back. I like that. – Matthias Dec 08 '21 at 11:49
  • @Matthias exactly - and `numpy.arange` works the same way as well – nikeros Dec 08 '21 at 12:44

1 Answers1

3

just create your own function. as changing the way a well-used function will cause many existing python programs to not work.

def range2(start, end):
    return list(range(start, end + 1))

use like

print(range2(1, 11))
Dean Van Greunen
  • 5,060
  • 2
  • 14
  • 28