This is a good question. The reason why this happens is because the default arguments to functions are stored as single objects in memory, not recreated every time you call the function.
So when you have a list []
as a default argument, there will only be one list forever for the duration of that program. So when you add to the list you are adding to that one copy of the list. This is still true for numbers like 5
. However, numbers are immutable in Python, and so when you alter a default argument that starts at a number, you're really making it point to a new number and not editing that 5
object, whereas many operations on lists mutate the list in place rather than returning a new list.
http://docs.python.org/3/tutorial/controlflow.html#default-argument-values
Important warning: The default value is evaluated only once. This
makes a difference when the default is a mutable object such as a
list, dictionary, or instances of most classes.
The recommended solution, if you need the behaviour of an empty list default argument without having the same empty list default argument every call to the function, is to do this:
def f(a, L = None):
if L is None:
L = []
L.append(a)
return L
The creation of an empty list is now evaluated on individual calls to the function - not once.