Newbie question - default values of a function
Dennis.Benzinger at gmx.net
Wed Dec 22 23:18:06 CET 2004
> But why the following happens?
> ... i=i+1
> ... return (a, i)
> (2, 1)
> (3, 1)
> (5, 1)
> From Language Reference:
> "Default parameter values are evaluated when the function definition
> is executed. This means that the expression is evaluated once, when
> the function is defined, and that that same ``pre-computed'' value is
> used for each call. This is especially important to understand when a
> default parameter is a mutable object, such as a list or a dictionary:
> if the function modifies the object (e.g. by appending an item to a
> list), the default value is in effect modified. "
> Surely the variable i is a mutable object?
No, i is not mutable!
i is a name for a number object which is _not_ mutable
The line i=i+1 creates a new number object with the value 1 and gives it
the name i.
More information about the Python-list