Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I think this should raise an error, but it doesn't

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)]
like image 219
user1794459 Avatar asked Nov 02 '12 14:11

user1794459


People also ask

What does it mean to raise an error?

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.

When should you raise type error?

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.

How do you raise errors in Python?

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.

What does raising an error mean in Python?

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.


1 Answers

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.

like image 123
mgilson Avatar answered Sep 29 '22 19:09

mgilson