0
Python and JavaScript equivalent functions but different outputs
I simply rewrote the JS function in Python expecting the output to be the same but turned out different? Why? What should I do to the Python function so that it yields the same output as JS? https://code.sololearn.com/chRNdY58ItaQ/?ref=app https://code.sololearn.com/W3TYqwq93byp/?ref=app
3 ответов
+ 2
Because default parameters are not handled the same way in Python and JS ^^
In JS, default argument values are assigned at runtime, while in Python, they are assign at function declaration time.
So, when you do:
def f(p,q=None):
... q will be the same list for each call, while in JS, q will be a new empty list at each call ;)
You rather need to translate the JS behavior by doing:
def f(p,q=None):
q = q or []
0
Cleared!
Thank you to both visph and Mirielle[Inactive] :)