Modifying the default argument of function

emile emile at fenx.com
Tue Jan 21 14:20:15 EST 2014


Function defs with mutable arguments hold a reference to the mutable 
container such that all invocations access the same changeable container.

To get separate mutable default arguments, use:

def f(x=None):
   if x is None: x=[2,3]

Emile

On 01/21/2014 11:11 AM, Mû wrote:
> Hi everybody,
>
> A friend of mine asked me a question about the following code:
>
> [code]
> def f(x=[2,3]):
>      x.append(1)
>      return x
>
> print(f())
> print(f())
> print(f())
> [/code]
>
> The results are [2, 3, 1], [2, 3, 1, 1] and [2, 3, 1, 1, 1].
>
> The function acts as if there were a global variable x, but the call of
> x results in an error (undefined variable). I don't understand why the
> successive calls of f() don't return the same value: indeed, I thought
> that [2,3] was the default argument of the function f, thus I expected
> the three calls of f() to be exactly equivalent.
>
> I'm don't know much about python, does anybody have a simple explanation
> please?
>





More information about the Python-list mailing list