Interface of the set classes

Steven Bethard steven.bethard at gmail.com
Fri Oct 29 12:45:39 EDT 2004


Pierre Barbier de Reuille <pierre.barbier <at> cirad.fr> writes:
>
> For me, sets are first sequences. I use set where lists are inefficient 
> or inadapted, for example when I need to remove redundancy and that I 
> don't care about the positions of my elements.

If you still need a fixed ordering after removing duplicates, why don't you just
revert to a list?

>>> l = [11, 1, 2, 2, 3, 5, 11, 3, 7, 5]
>>> list(set(l))
[1, 2, 3, 5, 7, 11]
>>> d = list(set(l))
>>> d[3]
5

Of course, if you want to maintain the order that items are inserted, you can
easily do this manually:

>>> class orderedset(set):
... 	def __init__(self, seq):
... 		super(set, self).__init__()
... 		self._items = []
... 		for item in seq:
... 			self.add(item)
... 	def add(self, item):
... 		if item not in self:
... 			self._items.append(item)
... 		set.add(self, item)
... 	def __iter__(self):
... 		return iter(self._items)
... 	def __getitem__(self, i):
... 		return self._items[i]
... 
>>> list(orderedset([11, 1, 2, 2, 3, 5, 11, 3, 7, 5]))
[11, 1, 2, 3, 5, 7]
>>> orderedset([11, 1, 2, 2, 3, 5, 11, 3, 7, 5])[2:4]
[2, 3]

And, while you're writing your own class to do this, you can change your method
names to append, etc. if you like.  =)

The point here, I guess, is that the uses you intend for sets probably do not
align so well with the uses everyone else has for sets.  Personally, I don't
expect any ordering in a set, and if I need such ordering I convert back to a
list.  I also almost never use the lst[x] syntax, preferring in general to just
iterate with a for-loop (or list comprehension, or generator expression...)  If
you find you do need the lst[x] syntax all the time, first, I'd double-check to
see if I couldn't write things better with a for-loop, and then, if I was still
pretty sure I couldn't, I'd write my orderedset class as above...

Steve




More information about the Python-list mailing list