Lists & "pointers"

George Sakkis gsakkis at rutgers.edu
Sat Jul 23 19:18:59 CEST 2005


<rixil at hotmail.com> wrote:

> Jan Danielsson wrote:
> > Hello all,
> >
> >    I have written a simple whiteboard application. In my application, I
> > want to be able to set draw attributes. This part works. I have a
> > dictionary object which contains stuff like:
> > self.attr['Pen.Color'] = ...
> > self.attr['Pen.Thickness'] = ...
> >
> >    Now, the problem is that I want to be able to store attributes in a
> > list so they'll be easily accessed using the function keys. I.e. I have
> > the "current attributes" which I want to be able to store or retrieve
> > in/from a list,
> >
> > The problem is that I have initialized the list like this:
> >
> > self.drawAttr = { blah, blah, blah.. }
> > self.storedAttr = [ ]
> > for i in range(0, 10):
> >    self.storedAttr.append(self.drawAttr)
> >
> >    I know what the problem is; they are all referencing the *same*
> > dictionary object. So, my question is: How do I initialize a list of
> > dictionary objects, where each list entry is its own object (which is a
> > copy from the self.drawAttr object).
> >
> > Also, how do I store/restore entries to the list?
> >
> >    I have found the "copy" module, and it's copy method. I assume this
> > would work:
> >
> > for i in range(0, 10):
> >    self.storedAttr.append(copy.copy(self.drawAttr))
> >
> >    However, the concept of "deep copy" confuses me. Do I want it, or
> > don't I want it? I repeat: the attributes object is a simple dictionary.
> >
> > Thankful for any advice.
>
> The easiest way to do it would be to create a new dictionary object for
> each iteration of your loop.  In this scenario, you would not need to
> use the copy module.
>
> In other words:
>
> self.storedAttr = [ ]
> for i in range(0, 10):
>     self.storedAttr.append({ blah, blah, blah.. })

And this would be equivalent to shallow copy. Whether you need a deep copy depends on what each
"blah" is. More specifically it depends on whether the values of the dictionary are mutable or not
(the keys are known to be immutable anyway). If they are immutable, a shallow copy is enough. If
not, check whether all dictionaries refer to the same values or separate copies of the values. Only
in the latter case you need deep copy.

HTH,

George





More information about the Python-list mailing list