Python - Mutable Default Arguments To Functions
Solution 1:
This is because each time you call f
it performs L=x
, as x
is a default value for L
on you argument list of f
.
So every time it actually appends to x
.
Solution 2:
It's not that the value of L
is shared, rather that the default value of L
as defined when the function is created is shared. In this case that's the list that starts as [4, 5]
.
If you specify a different value for L
when you call f
(as you do in the first call) then that is what is used and it's not shared with other calls.
If you don't specify any value for L
, then it uses the default value (as you'd expect), which is shared.
Anyway, in case it wasn't clear, don't use mutable default values. If you want some behaviour that can be conveniently done using mutable default values, do it manually. Even if the code is slightly longer, it will be more explicit, predictable, and readable.
Post a Comment for "Python - Mutable Default Arguments To Functions"