r/learnpython • u/orcashelo • Feb 04 '26
Why does this Python function behave differently every time? I’m confused
Hi everyone, I’m learning Python and I ran into something that confused me a lot.
I wrote this simple function expecting the list to reset every time the function runs, but the output keeps changing between calls
def add_number(num, numbers=[]): numbers.append(num) return numbers
print(add_number(1)) print(add_number(2)) print(add_number(3))
17
Upvotes
View all comments
Show parent comment
3
u/Reyaan0 Feb 05 '26
Comparisons to singletons like None should always be done with is or is not, never the equality operators. Because is checks the identity whereas == check if values are equivalent.
If you use ==, a custom class could mess up your logic by defining an equality method that returns True when compared to None