Do not use mutable objects as default arguments in Python

This Python peculiarity can lead to some unexpected behavior of your programs.

Timur Bakibayev, Ph.D.
Geek Culture

--

Say, you want a function that appends some data to a list. And if the list is not passed, then appends the same data to a newly created list.

What would be the obvious and naive way to go? Sure, why not use default arguments here? Let’s have a look at the code:

def append_10(the_list=[]):
the_list.append(10)
return the_list

Now, let’s try to execute this code:

my_list = [5]
print(append_10(my_list))

We will get the desired list [5,10] here. Let us now try out the default argument.

print(append_10())

What do we get? 10? Try to run it. Works? Fine. Don’t touch it then. Don’t even run it again.

Ok, ok, try to run it again. What?! It doesn’t work anymore? Try again then. Do you get a list of more than one number? Why?

What is going on there?

The thing is that the default object is created at the moment the function is defined. And then this object is reused every time you don’t pass an argument.

--

--