0

To start, I've solved the problem already, but want to learn more about why it's happening. Recently I ran into the an issue where I had setup a function which has a list as default value. Then in the function I appended some values into that list.

Then I ran the function twice and somehow the list remained in memory and the values were appended again.

I had setup a function as below using Python 3.6.8:

def function_a(x = []):
    for item in ["X", "Y", "Z"]:
        x.append(item)
    return x

and then I ran it twice and the following occurs:

function_a()
['X', 'Y', 'Z']

function_a()
['X', 'Y', 'Z', 'X', 'Y', 'Z']

I tried to find out why it's happening and couldn't find out by googling. Maybe you can help me out on understanding this =)

1 Answers1

0

Mutable default parameters are generally not the best idea.

Your question has already be answered here: "Least Astonishment" and the Mutable Default Argument

Zbiggi
  • 26
  • 2