[Python-Dev] Sets: elt in dict, lst.include

Ka-Ping Yee ping@lfw.org
Tue, 23 Jan 2001 11:27:38 -0800 (PST)

On Tue, 23 Jan 2001, Jeremy Hylton wrote:
> For my applications, the dictionary-based approach is faster and
> offers a natural interface.

The only change that needs to be made to support sets of immutable
elements is to provide "in" on dictionaries.  The rest is then all
quite natural:

    dict[key] = 1
    if key in dict: ...
    for key in dict: ...

(Then we can also get rid of the ugly has_key method.)

For those that need mutable set elements badly enough to sacrifice
a little speed, we can add two methods to lists:

    lst.include(elt)   # same as - if elt not in lst: lst.append(elt)
    lst.exclude(elt)   # same as - while elt in lst: lst.remove(elt)

(These are generally useful methods to have anyway.)

This proposal has the following advantages:

    1. You still get to choose which implementation best suits your needs.

    2. No new types are introduced; lists and dicts are well understood.

    3. Both features are extremely simple to understand and explain.

    4. Both features are useful in their own right, and could stand as
       independent proposals to improve lists and dicts respectively.
       (For instance, i spotted about 10 places in the std library where
       the 'include' method could be used, and i know i would use it
       myself -- certainly more often than pop or reverse!)

    5. In all cases this is faster than a new Python class.  (For instance,
       Jeremy's implementation even contained a commented-out optimization
       that stored self.elts.has_key as self.has_elt to speed things up a
       bit.  Using straight dicts would see this optimization and raise it
       one, with no effort at all.)

    6. Either feature can be independently approved or rejected without
       affecting the other.

-- ?!ng