How do you justify this rather odd behavior of functions working with lists? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How do you justify this rather odd behavior of functions working with lists?

https://code.sololearn.com/chE1ZM58mVb0/?ref=app

25th Feb 2020, 7:25 PM
【𝓪𝓈𝒽𝓴𝓪ℕ♦ℝ𝓪𝓷𝒿𝓫𝓪𝓇】
【𝓪𝓈𝒽𝓴𝓪ℕ♦ℝ𝓪𝓷𝒿𝓫𝓪𝓇】 - avatar
4 Answers
+ 3
In order to always use an empty list if this parameter is not provided, you have to rewrite the function like this: def f(x,y=None): if not y: y = [] In this way the list creation remains in local scope and invoked every time when calling the function. This is one of the common pitfalls in Python, using a mutable value (list in this case) as default argument.
25th Feb 2020, 7:43 PM
Tibor Santa
Tibor Santa - avatar
+ 4
Actually it's all logical. A function f has an attribute __defaults__. You can access it like any other class attribute. When you define default args, the values are stored in that defaults tuple *once* when the function is defined. Whenever you call f and don't pass that argument, the function will store the value from the __defaults__ in there. And when you put a list as a default argument, it will always be that very same list you're pulling out.
25th Feb 2020, 7:41 PM
HonFu
HonFu - avatar
+ 3
Whoa, thx guys, that solved everything. Unfortunately I can't mark all the answers as right, but to me all of you were helpful. Much obliged 🙏🏼🙏🏼 Tibor Santa, HonFu and last but not least Seb TheS
25th Feb 2020, 7:48 PM
【𝓪𝓈𝒽𝓴𝓪ℕ♦ℝ𝓪𝓷𝒿𝓫𝓪𝓇】
【𝓪𝓈𝒽𝓴𝓪ℕ♦ℝ𝓪𝓷𝒿𝓫𝓪𝓇】 - avatar
+ 2
The default argument always uses the same value, if you change the value you will always get the modified value when you use the default argument.
25th Feb 2020, 7:31 PM
Seb TheS
Seb TheS - avatar