Retaining order while using Python's set difference

python, set

Solution

It looks like you need an ordered set instead of a regular set.

>>> x = [1, 5, 3, 4]
>>> y = [3]
>>> print(list(OrderedSet(x) - OrderedSet(y)))
[1, 5, 4]

Python doesn't come with an ordered set, but it is easy to make one:

import collections.abc

class OrderedSet(collections.abc.Set):
    def __init__(self, iterable=()):
        self.d = collections.OrderedDict.fromkeys(iterable)

    def __len__(self):
        return len(self.d)

    def __contains__(self, element):
        return element in self.d

    def __iter__(self):
        return iter(self.d)

Hope this helps :-)

Problem

I'm doing a set difference operation in Python: ``` x = [1, 5, 3, 4] y = [3] result = list(set(x) - set(y)) print(result) ``` I'm getting: ``` [1, 4, 5] ``` As you can see, the order of the list elements has changed. How can I retain the list `x` in original format?

Original source