Counterintuitive Python behavior

Terry Reedy tejarex at yahoo.com
Wed Apr 17 11:09:13 EDT 2002


<dominikush at yahoo.com> wrote in message
news:3CBD1C02.8AB2CF62 at yahoo.com...

Preliminary note: over-riding the builtin constructor function names
'list' and 'dict' with program values is a bad habit to get into.  So
I modified the quotes.

vlist = ddict.values()
...
> However, if a dictionary has lists as value entries, I get
> a counterintuitive behavior (which, just recently, broke my
> code): If you change the dict, the list you previously
> created via ddict.values() gets automagically updated

The only list created by ddict.values() is the list of references to
the values in ddict.

> >>> ddict['a']=3

This changes the reference to 2 to a new reference to 3.
ddict.values() is changed and now different from vlist.

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

This does not change the reference bound to a and hence ddict.values()
is unchanged and still equal to vlist.  It uses the reference bound to
'a' to access and change the list, but *this* change is invisible to
ddict.

Terry J. Reedy








More information about the Python-list mailing list