Reputation: 13386
Is there an equivalent to python set
for non-hashable objects? (For instance custom class that can be compared to one another but not hashed?)
Upvotes: 6
Views: 3130
Reputation: 20272
There is the sortedset class from the blist library, which offers a set-like api for comparable (and potentially non-hashable) objects, using a storage mechanism based on a sorted list.
Upvotes: 0
Reputation: 1122282
If your values are not hashable, then there is no point in using set
.
Just use a list
instead. If all your objects can do is test for equality, then you'd have to scan each element every time to test for membership. obj in listvalue
does just that, scan the list until an equality match is found:
if not someobj in somelist:
somelist.append(someobj)
would give you a list of 'unique' values.
Yes, this is going to be slower than a set, but sets can only achieve O(1) complexity through hashes.
If your objects are orderable, you could speed up operations by using the bisect
module to bring down tests to O(log N) complexity, perhaps. Make sure you insert new values using the information gleaned from the bisection test to retain the order.
Upvotes: 11