Why Range function consider given one argument as stop value and not as start

Viewed 57

Why does the range() function—when given only one argument—consider the argument to be the stop value, when the stop value is the second argument when calling range() when two arguments?

According to Python, default arguments of functions should be defined at the back of the other arguments.

2 Answers

This function does not follow the normal Python conventions. It actually looks at the number of arguments, and then chooses how to interpret them. One argument? It's the stop value. Two? These are start and stop.

The reason is, of course, tradition and backwards compatibility. But also readability: range(n) is the most frequent case by far, and you don't want it to be e.g. range(stop=n). OTOH if you want both bounds of the range, then the only natural way is to write them as range(m, n), the first position must be taken by the left boundary.

This is why the authors of Python had to implement this kind of "magic", normally uncharacteristic to Python, and this is why it cannot be nicely represented by one signature.

One can consider many ways to make a completely clean design for range construction, without such discrepancies, but backwards compatibility dictates that range as is is here to stay for a loooong time.

Range has two "constructors" let's say, from sources:

class range(object):
    """
    range(stop) -> range object
    range(start, stop[, step]) -> range object
    
    Return an object that produces a sequence of integers from start (inclusive)
    to stop (exclusive) by step.  range(i, j) produces i, i+1, i+2, ..., j-1.
    start defaults to 0, and stop is omitted!  range(4) produces 0, 1, 2, 3.
    These are exactly the valid indices for a list of 4 elements.
    When step is given, it specifies the increment (or decrement).
    """
Related