Using None as a Sentinal

Below are my notes. I don’t understand how or why multiple calls to add_author won’t include data from previous calls to add_author. Can someone please explain this to me?

Using None as a Sentinel

So, if we want an empty list as an argument for a function, we can use None as a special value to indicate we did not receive anything. After we check whether an argument was provided we can instantiate a new list if it wasn’t.

def add_author(authors_books, current_books=None):
if current_books is None:
current_books = []

current_books.extend(authors_books)
return current_books

In the above function, we accept current_books a value expected to be a list. But we don’t require it. If someone calls add_author() without giving an argument for current_books, we supply an empty list. This way multiple calls to add_author won’t include data from previous calls to add_author.

The extend() method adds the specified list elements (or any iterable) to the end of the current list

Using the list literal notation name = [] creates an entirely new list every time it is executed. This is is contrast to using a mutable default argument which is only ever created once when the function is first executed and therefore can be subject to modification with repeated function calls (potentially leading to unexpected behaviour).

If this is from a particular lesson it is often worthwhile linking the lesson in addition to laying out your problem.

1 Like

Thanks for your reply! I understand that but I don’t understand why using None as a sentinel stops this from happening.