Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the function set use to check if two objects are different?

Simple code:

>>> set([2,2,1,2,2,2,3,3,5,1])
set([1, 2, 3, 5])

Ok, in the resulting sets there are no duplicates. What if the object in the list are not int but are some defined by me? What method does it check to understand if they are different? I implemented __eq__ and __cmp__ with some objects but set doesn't seems to use them :\

Does anyone know how to solve this?

like image 739
Andrea Ambu Avatar asked Dec 08 '08 23:12

Andrea Ambu


1 Answers

According to the set documentation, the elements must be hashable.

An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() or __cmp__() method). Hashable objects which compare equal must have the same hash value.

EDIT: added proper Hashable definition thanks to Roberto

like image 170
Adam Rosenfield Avatar answered Nov 14 '22 22:11

Adam Rosenfield