Topic Progress:

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

1
 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”:

1
items=[]

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”.

1
items.appends("some value") #this adds "some value" into items.

What do you expect the output will be? Turns out it’s this.


1
2
3
4
Output:
['something']
['something', 'something']
['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.



1
2
Output:
['something']
Categories:

2 Comments

Mark · June 17, 2019 at 11:12 pm

Can you explain what “items.append” does?

    fibg4 · June 19, 2019 at 2:30 pm

    “items” is a List. We will cover Lists in greater detail under the chapter on “Data Structures” later on. For now, just think of it as a kind of variable that can hold multiple values.

    “appends” is a method that adds values into items. Don’t worry about the details for Lists right now. Just assume that “appends” is going to insert something into items.

Leave a Reply

Your email address will not be published. Required fields are marked *