Why is dictionary.keys() a list and not a set?

Mike Meyer mwm at mired.org
Thu Nov 24 18:29:09 CET 2005


Christoph Zwerschke <cito at online.de> writes:
> - Because sets can only contain immutable values

Not true. Sets can only contain *hashable* objects, which isn't the
same thing.

> This, of course, in turn raises the question ;-) Would it be desirable
> to have an additional, more general set datatype that can contain
> mutable objects?

You can do that now:

>>> from UserList import UserList
>>> class HashableList(UserList):
...  def __hash__(self): return id(self)
... 
>>> s = set([HashableList(), HashableList()])
>>> s
set([[], []])
>>> for x in s:
...  x.append(3)
... 
>>> s
set([[3], [3]])

This also illustrates the danger of this approach, in that I've got
two lists that will compare equal in the same set:

>>> x = list(s)
>>> x[0] == x[1]
True

Of course, in this case the two objets aren't the same, which is what
is required for the mathematical definition of list:

>>> x[0] is x[1]
False

        <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list