Reciprocal data structures

Chris Angelico rosuav at gmail.com
Sun Jun 18 16:04:57 EDT 2017


On Mon, Jun 19, 2017 at 5:27 AM,  <pavlovevidence at gmail.com> wrote:
> I am thinking of a list that actively maintains in its items a member that contains the item's own index in the list.  Basically, the item knows its index into the list and the list ensures that the index remains in sync.  If the list is changed, the list updates the indices.  This is a the that might be useful in implementing observer pattern.
>

With a list? No, I would say it's a bad idea. But with a dictionary,
you certainly can. Consider something that loads up something based on
its unique ID (which could be a number or a string or something), and
then the thing itself has that ID. Very common in databasing, for
instance. You can then have a lookup dictionary where you grab them
from your cache, and the objects themselves have a "foo.id" attribute.
The IDs are immutable and eternal, unlike list indices, and they are
truly a feature of the object, so this makes a lot of sense. And it's
something I've done reasonably often.

ChrisA



More information about the Python-list mailing list