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)]
Raising an Error is a programmers way of saying "something went wrong", in a very specific way. For an analogy, when a flag in a football game is thrown, it means a penalty has been committed.
TypeError is raised whenever an operation is performed on an incorrect/unsupported object type. For example, using the + (addition) operator on a string and an integer value will raise TypeError.
As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.
raise allows you to throw an exception at any time. assert enables you to verify if a certain condition is met and throw an exception if it isn't. In the try clause, all statements are executed until an exception is encountered. except is used to catch and handle the exception(s) that are encountered in the try clause.
There's a check if item in uniq
which gets executed before the item is removed. The and
operator is nice in that it "short circuits". This means that if the condition on the left evaluates to False
-like, then the condition on the right doesn't get evaluated -- We already know the expression can't be True
-like.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With