Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

So 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?

like image 292
Ceasar Bautista Avatar asked Jul 10 '11 23:07

Ceasar Bautista


People also ask

Which is the default value of range () function?

The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number.

What are the parameters of the range function in Python?

Python range function has basically three arguments. Start: Integer representing the start of the range object. Stop: Integer representing the end of the range object. Step(optional): Integer representing the increment after each value.

How can default parameter be set in a user defined function in Python?

Introduction to Python default parameters When you define a function, you can specify a default value for each parameter. In this syntax, you specify default values ( value2 , value3 , …) for each parameter using the assignment operator ( =) .

Does Python have default parameters?

Python allows function arguments to have default values. If the function is called without the argument, the argument gets its default value.


2 Answers

Others have shown how it can be done using argument counting. If I were to implement it myself in Python, though, I'd do it more like this.

def range(start, limit=None, stride=1):
    if limit is None:
        start, limit = 0, start
    # ...
like image 172
kindall Avatar answered Sep 25 '22 01:09

kindall


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.

like image 33
MRAB Avatar answered Sep 27 '22 01:09

MRAB