Something in the function tutorial confused me.
greg
greg at cosc.canterbury.ac.nz
Tue Aug 7 22:33:01 EDT 2007
Steve Holden wrote:
> OK. The difference is that [] is a mutable value, while None is
> immutable.
No, it's not. It has nothing to do with mutability
vs immutability.
The difference is that in the first version the
expression [] is evaluated only *once*, when the
function is defined. Therefore there is just one
list object getting re-used.
In the second version, the expression [] gets
evaluated *each* time the function is called,
creating a new list object each time.
> When the function starts out with None as y's value any assignment to y
> causes it to reference a different value (since None is immutable).
You're confused. Assigning to y simply causes it
to reference whatever object is being assigned.
This is always true, regardless of what y was
referencing before.
To see that the immutability of None has nothing
to do with it, try the following version:
def f(x, y = []):
y = []
y.append(x)
print y
f(17)
f(42)
Try to work out what it will do, then try it, and
see if you understand why it does what it does.
--
Greg
More information about the Python-list
mailing list