Product SiteDocumentation Site

9.3. Default argument value

In a function variables may have default argument values, that means if we don't give any value for that particular variable it will assigned automatically.
>>> def test(a , b = -99):
...     if a > b:
...         return True
...     else:
...         return False

In the above example we have written b = -99 in the function parameter list. That means of no value for b is given then b's value is -99. This is a very simple example of default arguments. You can test the code by
>>> test(12, 23)
False
>>> test(12)
True

Important

Remember that you can not have an argument without default argument if you already have one argument with default values before it. Like f(a, b=90, c) is illegal as b is having a default value but after that c is not having any default value.

Also remember that default value is evaluated only once, so if you have any mutable object like list it will make a difference. See the next example
>>> def f(a, data=[]):
...     data.append(a)
...     return data
...
>>> print f(1)
[1]
>>> print f(2)
[1, 2]
>>> print f(3)
[1, 2, 3]

To avoid this you can write more idiomatic Python, like the following
>>> def f(a, data=None):
    if data is None:
        data = []
    data.append(a)
    return data

>>> print f(1)
[1]
>>> print f(2)
[2]