def append(num, to=[]): to.append(num) return to aa = append(1) print aa bb = append(2) print bb
We just call a function which default value should be initialized to an empty list, so the final output is supposed to be:
[1,] [2,]
But that's wrong answer. Python will output this:
[1,] [1, 2,]
The reason of that is that mutable default value can be modified! What I mean is that 'default' value for mutable type is not fixed anymore. If we mutate mutable parameter, its default value is also mutated and saved in the function's scope until next call.
No comments:
Post a Comment