Very often there is a need to set a default value to a function argument.
Earlier in the course we looked at the parameters of the print function
def print(self, *args, sep=' ', end='\n', file=None): ...
As you can see, sep, end and file have default values because core Python developers assumed that in most cases you just want to print things with a space in between them, a newline at the end and to a terminal console instead of a file.
If they didn’t set the default values you would have to provide them yourself every single time you wanted to print something. Imagine that for a second.
However not everything can be used as a default value. Have a look at this example. In this example, note that the following code is an “empty list”:
Don’t worry about this. We will cover lists in more details later. For now, just know that it is a kind of variable that can hold multiple values. To add a value into the list you need to use the “appends” method. Don’t worry about the details surrounding items. We will cover that in greater detail later on when we come to “Data Structures”.
items.appends("some value") #this adds "some value" into items.
What do you expect the output will be? Turns out it’s this.
['something', 'something', 'something']
Probably not what you expected. But can you guess why did this happen?
You see, in Python every single line of code is executed one by one. Top to bottom and left to right.
When the first line was executed runtime remembered that now there is a function simple_function that has a parameter with default value of an empty list. But every time you execute this function the same default list will be used. That is why the more and more values were added to the list as you ran the code. That principle holds true to any data structure used as a default value.
So what should you do instead? In cases like this it is a Python convention to use None as a default value. You then need to check if items is None and if it is create a new list.