Below is a simple function to remove duplicates in a list while preserving order. I’ve tried it and it actually works, so the problem here is my understanding. It seems to me that the second time you run uniq.remove(item) for a given item, it will return an error (KeyError or ValueError I think?) because that item has already been removed from the unique set. Is this not the case?
def unique(seq):
uniq = set(seq)
return [item for item in seq if item in uniq and not uniq.remove(item)]
There’s a check
if item in uniqwhich gets executed before the item is removed. Theandoperator is nice in that it “short circuits”. This means that if the condition on the left evaluates toFalse-like, then the condition on the right doesn’t get evaluated — We already know the expression can’t beTrue-like.