Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set of non hashable objects in python

Tags:

python

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?)

like image 694
Tzach Avatar asked Mar 22 '23 10:03

Tzach


1 Answers

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.

like image 114
Martijn Pieters Avatar answered Apr 02 '23 06:04

Martijn Pieters