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.
Python's None: Null in Python
dwalsh on July 29, 2020
At around 1:30 I see the following steps:
starter_list = [1,2,3]
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.