This happens because functions in Python are first-class objects:
Default parameter values are evaluated when the function definition is
executed. This means that the expression is evaluated once, when the
function is defined, and that the same “pre-computed” value is used
for each call.
It goes on to explain that editing the parameter value modifies the default value for subsequent calls, and that a simple solution of using None as the default, with an explicit test in the function body, is all that is needed to ensure no surprises.
Which means that def foo(l=[]) becomes an instance of that function when called, and gets reused for further calls. Think of function parameters as becoming apart of an object's attributes.
Pro's could include leveraging this to have classes have C-like static variables. So it's best to declare default values None and initialize them as needed:
class Foo(object):
def bar(self, l=None):
if not l:
l = []
l.append(5)
return l
f = Foo()
print(f.bar())
print(f.bar())
g = Foo()
print(g.bar())
print(g.bar())
yields:
[5] [5] [5] [5]
instead of the unexpected:
[5] [5, 5] [5, 5, 5] [5, 5, 5, 5]