Skip to content Skip to sidebar Skip to footer

The Strange Arguments Of Range

The range function in python3 takes three arguments. Two of them are optional. So the argument list looks like: [start], stop, [step] This means (correct me if i'm wrong) there is

Solution 1:

range() takes 1 positional argument and two optional arguments, and interprets these arguments differently depending on how many arguments you passed in.

If only one argument was passed in, it is assumed to be the stop argument, otherwise that first argument is interpreted as the start instead.

In reality, range(), coded in C, takes a variable number of arguments. You could emulate that like this:

def foo(*params):
    if 3 < len(params) < 1:
        raise ValueError('foo takes 1 - 3 arguments')
    elif len(params) == 1
        b = params[0]
    elif:
        a, b = params[:2]
    c = params[2] iflen(params) > 2 else 1

but you could also just swap arguments:

def range(start, stop=None, step=1):
    if stop isNone:
        start, stop =0, start

Solution 2:

range does not take keyword arguments:

range(start=0,stop=10)
TypeError: range() takes no keyword arguments

it takes 1, 2 or 3 positional arguments, they are evaluated according to their number:

range(stop)              # 1 argumentrange(start, stop)       # 2 argumentsrange(start, stop, step) # 3 arguments

i.e. it is not possible to create a range with defined stop and step and default start.

Solution 3:

def foo(first, second=None, third=1):
     if secondisNone:
         start, stop, step =0, first, 1else:
         start, stop, step =first, second, third

Solution 4:

As you know by now the real answer is that range is a C function which for some reason does not have the same rules of python (would be nice to know why).

People might hate me for suggesting this but I've being doing this for range since I have a terrible memory of what the order of things are. Imo this shouldn't be a problem so I'm fixing it:

range(*{'start':0,'stop':10,'step':2}.values())

the reason I made it a one liner is because I don't want to have to define a range function that needs to be defined everywhere or imported everywhere. This is pure python.

Post a Comment for "The Strange Arguments Of Range"