Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

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

I have this code

def func(data=[]):
     data.append(1)
     return data
func()
def append2(element, foo=[]):
    foo.append(element)
    return foo
print(append2(12))
print(append2(43))

When I run the code, I expect the following output

[12]

[43]

But the actual output is

 [12]

[12, 43]

Why is it that I am getting the output as shown?

ssues


1 Answer
Rajendra Dharmkar

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:

[12]

[43]

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=[]):
    data.append(1)
    return data
func()
func()
def append2(element, foo=None): 
    if foo is None:
        foo = []
    foo.append(element)
    return foo
print(append2(12))
print(append2(43))

OUTPUT

[12]
[43]

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.