Mutable Default Parameter Values
00:00 Let’s take a look at what can happen if you try to use a mutable object as a default parameter value in Python. This is a very classic example to demonstrate what’s happening with default values and mutable objects.
I have a function that’s going to append a string of three hashtags (
'###') to whatever list is passed as a parameter. And if it doesn’t have a parameter, then an empty list is created and the hashtag string is appended to that.
It doesn’t particularly care what the list looks like. If I give it a list of numbers,
f() says, “Okay! I’ll append the string to the end of that list.” And if I don’t provide a list,
f() is going to take its default value of an empty list and append the
'###' string to it.
And everything seems to be working just the way we expected until we call
f() without an argument a second time. We were expecting
f() to take an empty list and append the
'###' string to it, but that’s not what happened.
02:13 So, what’s happening here? In Python, the default value for a parameter value is defined only once. So when we imported that module and that function, Python executed it in a way that simply identified the name of the function, the name of the parameter, and its default value, and then it read the rest of the body of that function.
And each time the default value is
None, then we create a new list and then we append to whatever that list is. The point to make is that
my_list isn’t defined to a list at the definition execution.
06:07 The next few lessons are going to talk about how Python passes objects to a function and what you’re able to do with them, and compare it to other languages and how they choose to modify or not modify a parameter value that’s given to it.
Become a Member to join the conversation.