Default Arguments

  • + 1 comment
    • Mutable default arguments (like lists and dictionaries) in Python functions are created only once when the function is defined. If you don't provide your own argument when calling the function, it will keep using and modifying that same original mutable object across different calls, leading to unexpected results. The solution is to use None as the default and create a new mutable object inside the function if the default is used.

      Same problem can be found in below function. def add_to_list_bad(item, my_list=[]): my_list.append(item) return my_list