Search code examples
pythonset

Does Python have an ordered set?


Python has an ordered dictionary. What about an ordered set?


Solution

  • There is an ordered set (possible new link) recipe for this which is referred to from the Python 2 Documentation. This runs on Py2.6 or later and 3.0 or later without any modifications. The interface is almost exactly the same as a normal set, except that initialisation should be done with a list.

    OrderedSet([1, 2, 3])
    

    This is a MutableSet, so the signature for .union doesn't match that of set, but since it includes __or__ something similar can easily be added:

    @staticmethod
    def union(*sets):
        union = OrderedSet()
        union.union(*sets)
        return union
    
    def union(self, *sets):
        for set in sets:
            self |= set