Extending python & mutability

Steve Holden sholden at holdenweb.com
Thu Jun 28 15:17:06 EDT 2001


"John" <john.thai at dspfactory.com> wrote ...
> When extending python, if I have a function that is expecting a list whose
> contents are mutible, can I modify the contents and will the changes be
> reflected in back in Python?
>
>>> def change(a, l):
...  a = 34
...  l.append("extra")
...  return a, l
...
>>> a1 = 12
>>> l1 = ["nothing"]
>>> a2, l2 = change(a1, l1)
>>> a1, l1
(12, ['nothing', 'extra'])
>>> a2, l2
(34, ['nothing', 'extra'])

In other words, immutable arguments changed inside a function continue to
hold their original values (because you are only binding the argument name
to a new value). Mutable arguments changed inside a function will reflect
their updated values (since you have actually changed the value to which the
argument was bound).

As you can also see, a functioncan return a complex type like a tuple,
allowing you to return values based on immutable arguments in whatever
quantity you like.

regards
 Steve

--
http://www.holdenweb.com/








More information about the Python-list mailing list