Sorted list as an alternative to dictionary for when you only need keys?

Jeff Epler jepler at unpythonic.net
Mon Jul 19 16:44:15 EDT 2004


Python 2.3 and above have a 'sets' module.

>>> import sets
>>> s = sets.Set("cucumber")
>>> s
Set(['c', 'b', 'e', 'm', 'r', 'u'])
>>> t = s - sets.Set("cabbage")   
>>> t
Set(['u', 'r', 'm'])
>>> 'c' in s
True
>>> 'c' in t
False
>>> t.add('c')
>>> 'c' in t
True

The "in" test and the .add() method are as efficient as "in" and
item-assignment with dictionaries.

Python 2.2 and above also have a "bisect" module which can be used for O(lg n)
insertions, deletions, and searches for items in sorted lists, but
there's not a simple OO interface for it.

Jeff
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20040719/56d0289a/attachment.sig>


More information about the Python-list mailing list