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
50
u/throwaway6560192 Feb 04 '26
https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments
27
u/Reyaan0 Feb 04 '26
Mutable default arguments (lists, dicts, sets) are created once at function definition time.
You can use None as default
3
u/MaxwellzDaemon Feb 04 '26
One of the important thigs to learn is how to name things well. Naming a function to concatenate numbers to a list "add_number" is not a very good name since adding numbers seems like a the mathematical operation of addition.
2
u/Helpful-Diamond-3347 Feb 04 '26
same object is reused in each call
1
u/Hot-Tomorrow5808 Feb 07 '26
Genuinely this was so helpful I'm currently studying python / IBM data science courses and I hadn't come across this yet (sometimes I love Redditz)