0

I am trying to solve a puzzle in python and javascript and came across a problem.

Below python and javascript are giving different outputs but they are both interpreter languages. Any idea why they are working like this?

Python snippet

def func(a = list()):
    a.append(len(a))
    return a

print(func())
print(func())

output:

[0]
[0,1]

Javascript snippet

function func(a = []) {
    a.push(a.length); 
    return a
}

console.log(func())
console.log(func())

output:

[0]
[0]
  • 2
    Do the answers to this [question](https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument) help at all? – quamrana May 05 '23 at 13:02
  • 2
    They're different languages with different rules, the fact that their default implementation uses interpretation is irrelevant. – deceze May 05 '23 at 13:04
  • I would change the title to "Python and JavaScript: different default parameter behavior" – Walter Tross May 05 '23 at 23:09

1 Answers1

2

By specifying a default parameter, it will store it once, you thus modify and return the same list. This is one of the major reasons not to work with mutable values as default parameters.

Usually what one does is work with None, or some other variable, and turn this into a list, so:

def func(a=None):
    if a is None:
        a = []  # creating a new list
    a.append(len(a))
    return a

The default value is thus not stored as an expression. The expresion is evaluated when the function is compiled (for the first time) and then the result of that expression is reused each function call.

As for JavaScript, it will each time evaluate the expression again, and thus construct a new list.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555