Counterintuitive Python behavior

Max M maxm at mxm.dk
Wed Apr 17 09:09:26 EDT 2002


dominikush at yahoo.com wrote:

> Who is wrong here: my intuition or Python (2.2)? If it's
> my intuition, how can I train my thinking about Python's
> execution model, so that my intuition get's better ;-)

Your intuition!

Objects like lists gets copied by reference. So Python behaves exactly 
like it should.

Maybe it is clearer with another notation:

 >>> dict = {'a':<list ref1>,'b':<list ref2>}
 >>> list = dict.values()
 >>> list

[<list ref1>, <list ref2>]

 >>> dict['a'].append(3)
 >>> dict

{'a': <list ref1>, 'b': <list ref2>}

 >>> list

[<list ref1>, <list ref2>]


regards Max M




More information about the Python-list mailing list