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:
Sets are unordered, so you will need to put the results back in the correct order after doing your set difference. Fortunately you already have the elements in the order you want, so this is easy.
diff = set(x) - set(y)
result = [o for o in x if o in diff]
But this can be streamlined; you can do the difference as part of the list comprehension (though it is arguably slightly less clear that that's what you're doing).
sety = set(y)
result = [o for o in x if o not in sety]
You could even do it without creating the set
from y
, but the set
will provide fast membership tests, which will save you significant time if either list is large.