6 ms·
The Wat part is this: print(list1) # [1, 2] print(list2) # [1, 2] Some would expect it to be: print(list1) # [1] print(list2) # [2] The
by xdennis 4y ago
The Wat part is this:
print(list1) # [1, 2]
print(list2) # [1, 2]
Some would expect it to be:
print(list1) # [1]
print(list2) # [2]
The reason it's weird is because Python evaluates default arguments at function definition time rather that function call. This means that it's unsafe to use mutable values as default values in params. See the equivalent in JavaScript:
function addToList(value, targetList=[]) {
targetList.push(value);
return targetList;
}
const list1 = addToList(1);
const list2 = addToList(2);
console.log(list1); // [1]
console.log(list2); // [2]