Explain whats going on - Python | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

21st Jan 2018, 5:52 AM
Louis
Louis - avatar
5 Answers
+ 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
21st Jan 2018, 6:12 AM
John Wells
John Wells - avatar
+ 9
Thanks Sina. I wonder if there is any real world application for this.
21st Jan 2018, 10:07 AM
Louis
Louis - avatar
+ 8
Thanks John.
21st Jan 2018, 9:09 AM
Louis
Louis - avatar
+ 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.
21st Jan 2018, 10:14 AM
Sina Seirafi
Sina Seirafi - avatar
+ 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.
21st Jan 2018, 9:48 AM
Sina Seirafi
Sina Seirafi - avatar