+ 20

Declaration of variable - parameter in function header in python

I frequently see codes in sololearn which uses a user function like this: def test(val, arr = []): the arr parameter does not get an argument from the calling statement, so I think it is meant as a declaration of an list. This constellation gives a kind of unexpected behavior. I have done 2 samples of code doing exact the same except the way arr is declared. The function test1 and test2 are called each 3 times by passing a single character to the val variable. This character is appended to the arr in the function body, and finally the length of arr is returned. Does anybody have an idea why this is happening? Find more in the attached file. https://code.sololearn.com/cLE0cgu2yN64/?ref=app

26th Oct 2019, 11:12 AM
Lothar
Lothar - avatar
6 odpowiedzi
+ 18
Lothar This is because everything in python is an object. In that case list is a mutable object and its bad practice to pass mutable objects to either functions or methods. First declaration of the function whatever pass to the list argument and its a property of the function Second declaration of the function the list is pass inside the function body and is declared empty list at every call You can check this link to indepth explanation https://nikos7am.com/posts/mutable-default-arguments/ #greatObservation and question by the way
26th Oct 2019, 12:35 PM
BlackRose Mike
BlackRose Mike - avatar
+ 11
Lothar im glad i could be of help##
26th Oct 2019, 3:27 PM
BlackRose Mike
BlackRose Mike - avatar
+ 9
Black Rose Mike, thank you so much - that is exactly what happens to my sample. And your link is a really great source with explanations. I was searching a lot, but it was difficult to name it. Thanks agian!
26th Oct 2019, 2:57 PM
Lothar
Lothar - avatar
+ 8
M F Sorensen, I have checked this, both are class list. But thanks for your reply!
26th Oct 2019, 12:04 PM
Lothar
Lothar - avatar
+ 6
interesting question. perhaps it becomes a list in first example and a string in second?
26th Oct 2019, 11:49 AM
mpssolutionsdk
mpssolutionsdk - avatar
+ 5
👍🏼 also gave it very little chance as I believe you are pretty skilled 🤓
26th Oct 2019, 12:13 PM
mpssolutionsdk
mpssolutionsdk - avatar