Search code examples
pythonrangedefault-value

How does the Python range function have a default parameter before the actual one?


I'm writing a function that takes an optional list and extends it to the length specified. Rather than writing it as foo(n, list=None) I was wondering how I might emulate the behavior of Python's range function which works like:

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(5, 10)
[5, 6, 7, 8, 9]

That is, with the default parameter first. For reference trying to naively set this up returns a syntax error:

def foo(x=10, y):
    return x + y
SyntaxError: non-default argument follows default argument

So I'm wondering, is this hard-coded into range? Or can this behavior be emulated?


Solution

  • They aren't real keyword arguments.

    If there's one argument, it's the limit.

    If there are two arguments, the first is the start value and the second is the limit.

    If there are three arguments, the first is the start value, the second is the limit, and the third is the stride.