Modifying the default argument of function
Steve Jones
steve at secretvolcanobase.org
Tue Jan 21 14:19:53 EST 2014
On Tue, 21 Jan 2014 20:11:02 +0100
Mû <mu-- at melix.net> 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?
x is assigned to the list [2, 3] at the time the function is created not when the function is called, meaning that there's only ever 1 list created. When you call x.append this list is modified and the next time the function is called x still refers to this modified list.
More information about the Python-list
mailing list