views:

181

answers:

1

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?

+12  A: 

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

Adam Rosenfield
"if and only if" makes no sense, though. The hash might be used to pre-select equal items, but surely a direct comparison of the actual values must be happening, too, or the results of set comparisons would be rather random.
Thomas Tempelmann
From python documentation: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.
Roberto Liffredo
edited in roberto's response.
TheSoftwareJedi