YpsilonZett YpsilonZett - 8 months ago 42
Python Question

Deep understanding of pythons range function

I'm just wondering about some aspects of pythons range() function.

If you give it a single argument like

It will take this argument as the point to stop. If you give two args, it will take them as
start, stop
, and if you give three args, it will handle them as
start, stop, steps

How is it that the order of arguments changes? With one argument it's just "stop", but the docs say "start, stop, steps"!

For example, if I make a function with default parameters (I think, it has to do something with that), like
foo(bar=None, baz=None, arg=None)
, and call it like
foo(1, 2)
,"bar" will be 1 and "baz" will be 2.

Thank you for help.


If you want to do something similar, you can accept any number of arguments, and then manually raise errors if necessary

def foo(*args):
    if not args:
        raise TypeError("foo expected 1 arguments, got 0")
    elif len(args)>3:
        raise TypeError("foo expected at most 3 arguments, got {}".format(len(args)))

And then assign start = args[0] etc, based on len(args)