A question on modification of a list via a function invocation
Gregory Ewing
greg.ewing at canterbury.ac.nz
Fri Sep 8 03:54:28 EDT 2017
Steve D'Aprano wrote:
> py> class K: # defines an object
> ... def __init__(self, x):
> ... self.x = x
> ... def append(self, value):
> ... self.x.append(value)
> ...
> py> a = []
> py> b = K(a)
> py> a is b # these are not the same object (they're different types)
> False
> py> b.append(99) # but modifying b modifies a
> py> a
> [99]
You didn't mutate the object bound to b there,
you mutated the one bound to b.x, which is
also bound to a.
All you've shown is that just because a method
is named "append" doesn't mean it mutates the
object it's a method of. :-)
--
Greg
More information about the Python-list
mailing list