Apologies if this is anwered elsewhere; I'm new(ish) to Python and suspect that I'm not discovering something novel. I have tried searching for similar questions but might not have the right terminology for describing the problem.
I'm looking for an explanation of WHY the following happens, rather that HOW to avoid/fix the problem, as I'm pretty sure I can work around this in my program.
Here is a MVP version of what I'm seeing:
def my_func(func_value, func_list=[]):
func_list.append(func_value)
print(func_list)
my_func("a")
my_func("b", [])
my_func("c")
my_func("d", ["p", "q", "r"])
my_func("e")
Which returns the following. What surprised me was that the 3rd and 5th times I called the function printed output that appeared to remember the 1st and 3rd times the function had been called:
['a']
['b']
['a', 'c'] # <-- why isn't this just "c"
['p', 'q', 'r', 'd']
['a', 'c', 'e'] # <-- why isn't this just "e"
I have checked that i'm not somehow using a global variable for func_list
. I'm not returning anything from the function so I don't see how whatever is happening inside the function could "leak" into the parent scope.
Why is this happening?