How to store the reference of a dictionary element ?

Alfredo P. Ricafort alpot at mylinuxsite.com
Thu Dec 19 19:29:08 EST 2002


On Fri, 2002-12-20 at 06:38, Terry Reedy wrote:
> Any newbie who wants to write correct code should ignore this.  Two
> references to the same object are two references to the *same object*.
> If the object is mutable and is changed, then the change is visible no
> matter how you access it.  This is a common 'gotcha' for newbies who
> mistakenly think that assignment creates a copy, which it does not.
> To illustrate:
> 
> >>> d={}
> >>> d['p']=[1,2]
> >>> d['c']=[3,4,d['p']] # equivalent to what I wrote and quoted above
> >>> id(d['p']), id(d['c'][2])
> (7953824, 7953824)
> >>> d['p'].append(5) # a change to the parent value list
> >>> d['c'][2] # access via the child *does* see the change
> [1, 2, 5]
> 
> Terry J. Reedy

Hi Terry,

I understand that. That is why I said in my earlier post(to Terry
Hancock) that if I do this:

  a['2']=[22] 

instead of this:

  a['2'][0]=22

then the link will be broken.

Similarly, and following your example, if someone change the value of
d['p'] like this:
    
  d['p']=[1,2,5]

instead of this
  
  d['p'].append(5)

then d['c']'s reference to d['p'] will be lost.



AL













More information about the Python-list mailing list