[python-nl] some observations

Martijn Pieters mj at python.org
Tue Jan 10 15:47:20 CET 2006


Perdaen, D.M.L. wrote:
> Question 1: Why is it that the dictionary 'b' is global over the
> methods in scrips 1a and 1c and the result of 'print b' is { 'z' : 10 }?
> I would expect that dictionary 'b' would be created locally in 'subtest'
> and that it would stay empty in 'def test' just like in 'script 1b'. Can
> anybody explain the differences?

In Python, there is a distinct difference between values, and variables. 
Variables hold references to values. These references are like strings 
tied to the values. You can retie the variable string to another value, 
and two variables can both point to the same value.

Another important concept is mutability. Values can either be mutated, 
or they cannot. Dictionaries are mutable; they can be changed in place. 
Storing items in a dictionary means the dictionary value has changed.

With these concepts in mind, it becomes much easier to understand the 
scripts. When you pass around the contents of variables, you are passing 
round references. If that is a reference to a dictionary, then two 
variables can end up pointing to the same dictionary.

Changes made to that dictionary via one variable are then visible via 
any other reference to the variable. Passing a dictionary into a 
function and manipulating it there will result in a altered dictionary.

If you assingn a new dictionary to a variable, as in 1b, you retie the 
reference string to another value, and the varable no longer points to 
the passed-in dictionary.

> Question 2: In script 2a list 'b' stays the same as list 'a'. In
> scrips 2b int 'b' doesn't stay as int 'a'. Can anybody explain these
> differences?

Integers are immutable. Operations on integers result in new integers, 
to which the references can then be stored in variables again.

Lists on the other hand are mutable, and the script operates on the list 
values, not on the variable references.

Martijn Pieters




More information about the Python-nl mailing list