Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why doesn't this remove duplicates from my list?

class MyObject(object):

    def __init__(self, no, text):
        self.no = no
        self.text = text

    def __eq__(self, other):
        if isinstance(other, self.__class__):
            return self.text == other.text
        return False

    def __hash__(self):
        return hash(str(self))

my_list = {MyObject(1, 'a'), MyObject(2, 'a'), MyObject(0, 'b')}


print(my_list)

This still prints out 3 objects, but I want to remove one of the elements which has the same ‘a’. Why doesn’t it work? I defined the MyObject class for this de-duplication purpose.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You have to either change the hash method’s return value to hash(self.text), or, you can keep its return as hash(str(self)) and add a __str__ method whose return value is self.text.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading