I have a question about the range function. How is it that the function has three parameters (start, stop, step), but the mandatory one (stop) is in the MIDDLE? I thought mandatory parameters have to be at the beginning, and optional parameters come afterwards? When I try to create my own function with a mandatory parameter after an optional parameter, I get an error "non-default argument follows default argument". I suppose the actual implementation of range could make it only an illusion that the middle parameter is mandatory, and there's actually some work done behind the scenes. But I'm hoping someone knows the answer to this..?

For reference, here is the printing of help(range):

range([start,] stop[, step]) -> list of integers

Return a list containing an arithmetic progression of integers.
range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
When step is given, it specifies the increment (or decrement).
For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!
These are exactly the valid indices for a list of 4 elements.

If you would write range() in Python you would have to do something like this:

def range(start, stop=None, step=1):
    """if start is missing it defaults to zero, somewhat tricky"""
    if stop == None:
        stop = start
        start = 0
    # rest of the code here ...

range([start,] stop[, step]) -> list of integers
I'm just guessing but the definition would have to be something like this, although the actual code may be in C/C++

def range_test(*args_in):
   if len(args_in) == 1:
      print "one arg found", start, stop, step
      ## compare for length==2 and then 3 (error if < 1 or > 3)
      print len(args_in), "args found -->", args_in

This article has been dead for over six months. Start a new discussion instead.