Newbie question about reference

Gerhard Häring gh at ghaering.de
Sat Mar 22 16:50:35 EST 2003


* 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).

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]
#v-

Note that 'list' is a builtin type, so you better chose a variable name other
than 'list' (or 'dict', or 'str') in order to not hide any builtins.

HTH,

Gerhard
-- 
mail:   gh at ghaering.de
web:    http://ghaering.de/





More information about the Python-list mailing list