Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

None as a Default Parameter

Comments & Discussion

dwalsh on July 29, 2020

At around 1:30 I see the following steps:

  1. starter_list = [1,2,3]
  2. bad_function(4,starter_list) -> returns [1,2,3,4]
  3. bad_function(5) -> returns [5]
  4. bad_function(6) -> returns [5,6]

Christian explains the starter_list is being reused in steps 3 and 4 with the same memory id. Why did this reuse not occur between steps 2 and 3 then or put another way why did bad_function in line 3 not return [1,2,3,4,5]. I am thinking that when bad_function is run the starter_list resets to [] as the function defines the default that way. The video states it’s being reused in step 4 though. Why did this behavior not occur at step 3 then with the previous return of starter_list? Hope this question makes sense.

Bartosz Zaczyński RP Team on Aug. 3, 2020

Default function arguments are somewhat tricky in Python. The rule of thumb is to never use mutable types such as lists as default arguments because they create a kind of global variable that gets reused across function calls.

Python instantiates default argument values when it reads a function definition. That happens once when the interpreter loads the file rather than every time a function is called. That’s the most confusing part. Subsequent function calls won’t result in creating new lists but will resue the one already available.

Creating a new list manually within the function body fixes the problem. However, for immutable types such as strings and numbers, that would be unnecessary.

Become a Member to join the conversation.