+ 1

Why is “to” list not empty on second initialisation? And can we initialise a list in arguments of a function?

def build_list(element, to=[]): to.append(element) return to my_list = build_list(2) print(my_list) my_other_list = build_list(5) print(my_other_list) Output: [2] [2,5]

3rd Jan 2022, 4:10 AM
Nishant Srinet
Nishant Srinet - avatar
3 Réponses
+ 1
"Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. " https://docs.python.org/3.9/tutorial/controlflow.html#default-argument-values >>> def test(a=2, b=[]): ... b.append(a) ... return b ... >>> test.__defaults__ (2, []) >>> test(3) [3] >>> test.__defaults__ (2, [3]) >>> test(4) [3, 4] >>> test.__defaults__ (2, [3, 4])
3rd Jan 2022, 5:38 AM
FanYu
FanYu - avatar
+ 1
mutable object: >>> a = 1 >>> id(a) 1677375408 >>> a += 1 >>> id(a) 1677375424 >>> b = [] >>> id(b) 42097000 >>> b += [1] >>> id(b) 42097000 >>> c = tuple() >>> id(c) 3866664 >>> c += (1,) >>> id(c) 8845344
3rd Jan 2022, 6:03 AM
FanYu
FanYu - avatar
+ 1
Nishant Srinet As fan yu said, default arguments are evaluated only once. In your case, the list object '[]' is created and its reference is stored in the variable 'to' at the time of function creation. Whatever you do now, this function default argument cannot be changed whatsoever. This means that you are appending the integers to the same list object, hence the result. Hopefully this should explain the footprint (int '2') left by the previous function call.
3rd Jan 2022, 6:18 AM
Œ ㅤ
Œ ㅤ - avatar