+ 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
6 Antworten
+ 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
+ 11
Lothar im glad i could be of help##
+ 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!
+ 8
M F Sorensen, I have checked this, both are class list. But thanks for your reply!
+ 6
interesting question. perhaps it becomes a list in first example and a string in second?
+ 5
👍🏼 also gave it very little chance as I believe you are pretty skilled 🤓