Newbie question about reference

John Machin sjmachin at lexicon.net
Sat Mar 22 20:33:26 EST 2003


On Sat, 22 Mar 2003 22:50:35 +0100, Gerhard =?iso-8859-1?Q?H=E4ring?=
<gh at ghaering.de> wrote:

>* Tim Smith <tssmith at velocio.com> [2003-03-22 13:10 -0800]:
>> Something that this beginner does not understand about Python. Why
>> does the following--
>> 
>>  > python
>>  Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on
>> win32
>>  Type "help", "copyright", "credits" or "license" for more
>> information.
>>  >>> x = 1
>>  >>> y = 2
>>  >>> z = 3
>>  >>> list = [x, y, z]
>>  >>> list
>>  [1, 2, 3]
>>  >>> y = 0
>>  >>> list
>>  [1, 2, 3]
>>  >>>
>> 
>> do what it does?
>
>Immutable vs. mutable types. ints, floats, strings, tuples are immutable. lists
>and dictionaries are mutable (there are more types than these, so this is a
>nonexclusive list).

Que?

>
>So if, instead of an int, you use a dictionary, you get the effect you
>looked for:
>
>#v+
>Python 2.2.2 (#1, Jan 18 2003, 10:18:59)
>[GCC 3.2.2 20030109 (Debian prerelease)] on linux2
>Type "help", "copyright", "credits" or "license" for more information.
>>>> x, y, z = 1, {"key": 5}, -2
>>>> lst = [x, y, z]
>>>> lst
>[1, {'key': 5}, -2]
>>>> y["key"] = 6
>>>> lst
>[1, {'key': 6}, -2]
>>>> y["key2"] = 7
>>>> lst
>[1, {'key2': 7, 'key': 6}, -2]

If you use a dictionary instead of an int in Tim's example,  i.e. one
of the "variables" is bound to a new object, you get **exactly** the
same effect. See below. Nothing to do with mutability of the original
oject.  Concurring with Terry: funny, this is expected behaviour in
most languages, shouldn't need doco.

However if the original object is a mutable container, you can meddle
with the *contents* of that object and the meddling is then of course
visible through all references to that object.. Can be surprising, is
a FAQ,  needs doco, has doco(?) -- to lazy to look :-)

>>> x, y, z = 1, {"key":5}, 42
>>> lst = [x, y, z]
>>> lst
[1, {'key': 5}, 42]
>>> y = {"another":"dict"}
>>> lst
[1, {'key': 5}, 42]
>>>








More information about the Python-list mailing list