Reciprocal data structures

Steven D'Aprano steve at pearwood.info
Mon Jun 19 01:54:49 EDT 2017


On Mon, 19 Jun 2017 06:04:57 +1000, Chris Angelico wrote:

> 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.

How would you use this? Can you give some demonstration pseudo-code?


> With a list? No, I would say it's a bad idea.


Why a bad idea?

As opposed to "can't be done", or "too hard and slow".



> 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.



-- 
Steve



More information about the Python-list mailing list