+ 11
Explain whats going on - Python
This code is based on a Challenge question by Chullee Park which I got wrong. I was expecting that y will only have local scope. Now It seems that not only does y have global scope, there are 2 versions of it. please explain. https://code.sololearn.com/c2uUH0kcOjWa/?ref=app
5 Respostas
+ 10
There are not two y's in global scope. When you use the default instead of passing in the second argument, you get a persistent object, which will be reused for every other call.
https://docs.quantifiedcode.com/JUMP_LINK__&&__python__&&__JUMP_LINK-anti-patterns/correctness/mutable_default_value_as_argument.html
+ 9
Thanks Sina. I wonder if there is any real world application for this.
+ 8
Thanks John.
+ 5
I think there is. A function which adds arguments to lists, and to a default list if there is non specified.
It could be quite useful, if you can access the default list.
+ 4
Just as John said, there's a default value, or you can call any list as your second argument and it'll add the first argument to that list.
In your own example, there are three different lists at the end. (Notice 5 isn't in the same list as 2)
For me personally, it's interesting to know how you can access the default list, and work with it.