We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
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
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Default Arguments
You are viewing a single comment's thread. Return to all comments →
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