Original title: Why does this Python function append a value to a list on every call, even with an empty argument [duplicate]
I’m encountering a bizarre bug where my function seems to be “remembering” previous calls. I’ve simplified the code to demonstrate the issue: def append_to_list(value, my_list=[]): my_list.append(value) return my_list
First call works as expected
result1 = append_to_list(1) print(result1) # Output: [1]
Second call should return [2], but it doesn’t!
result2 = append_to_list(2) print(result2) # Output: [1, 2] # Wait, what? Where did the 1 come from?
I explicitly did not pass a list for my_list the second time, so I expected it to default to a new empty list [], resulting in [2]. Why is it reusing the list from the first call? Is this a bug in Python What’s the correct way to define this function so that it always uses a fresh empty list as the default?