Python 2: different meaning of the 'in' keyword for sets and lists
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: RPG Blues Looping
--
Chapters
00:00 Python 2: Different Meaning Of The 'In' Keyword For Sets And Lists
00:35 Accepted Answer Score 17
01:42 Answer 2 Score 1
01:56 Answer 3 Score 3
02:28 Thank you
--
Full question
https://stackoverflow.com/questions/9255...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #list #set #equality
#avk47
ACCEPTED ANSWER
Score 17
The meaning is the same, but the implementation is different. Lists simply examine each object, checking for equality, so it works for your class. Sets first hash the objects, and if they don't implement hash properly, the set appears not to work.
Your class defines __eq__, but doesn't define __hash__, and so won't work properly for sets or as keys of dictionaries. The rule for __eq__ and __hash__ is that two objects that __eq__ as True must also have equal hashes. By default, objects hash based on their memory address. So your two objects that are equal by your definition don't provide the same hash, so they break the rule about __eq__ and __hash__.
If you provide a __hash__ implementation, it will work fine. For your sample code, it could be:
def __hash__(self):
return hash(self.someattribute)
ANSWER 2
Score 3
In pretty much any hashtable implementation, including Python's, if you override the equality method you must override the hashing method (in Python, this is __hash__). The in operator for lists just checks equality with every element of the list, which the in operator for sets first hashes the object you are looking for, checks for an object in that slot of the hashtable, and then checks for equality if there is anything in the slot. So, if you override __eq__ without overriding __hash__, you cannot be guaranteed that the in operator for sets will check in the right slot.
ANSWER 3
Score 1
Define __hash__() method that corresponds to your __eq__() method. Example.