How to set default parameter values to a function in Python?

PythonServer Side ProgrammingProgramming

Python’s handling of default parameter values is one of a few things that can bother most new Python programmers.

What causes issues is using a “mutable” object as a default value; that is, a value that can be modified in place, like a list or a dictionary.

A new list is created each time the function is called if a second argument isn’t provided, so that the EXPECTED OUTPUT is:


A new list is created once when the function is defined, and the same list is used in each successive call.

Python’s default arguments are evaluated once when the function is defined, not each time the function is called. This means that if you use a mutable default argument and mutate it, you will and have mutated that object for all future calls to the function as well.

What we should do

Create a new object each time the function is called, by using a default arg to signal that no argument was provided (None is often a good choice).


def func(data=[]):
    return data
def append2(element, foo=None):
    if foo is None:
        foo = []
    return foo


Published on 07-Dec-2017 11:21:23