You need to implement some special methods in your class. Here is a quick example
if for some reason you don't want/are not able to change the class
class Person(): def __init__(self, name): self.name = name def __eq__(self, other): return (self.name, ) == (other.name, ) def __hash__(self): return hash((self.name,)) def __str__(self): return self.name person1 = Person('John') person2 = Person('Allice') person3 = Person('John') persons = [person1, person2, person3] print(persons) for person in persons: print(person) unique_persons = set(persons) print(unique_persons) for person in unique_persons: print(person)
Output:[<__main__.Person instance at 0x02FB1B20>, <__main__.Person instance at 0x02FB53F0>, <__main__.Person instance at 0x02FB5418>]
John
Allice
John
set([<__main__.Person instance at 0x02FB1B20>, <__main__.Person instance at 0x02FB53F0>])
John
Allice
>>>
note that I have added __str__() just for more clarity in the example outputif for some reason you don't want/are not able to change the class
class Person(): def __init__(self, name): self.name = name def __str__(self): return self.name person1 = Person('John') person2 = Person('Allice') person3 = Person('John') persons = [person1, person2, person3] print(persons) for person in persons: print(person) def dedup(persons): unique = [] unique_names = set() for person in persons: if person.name not in unique_names: unique.append(person) unique_names.add(person.name) return unique unique_persons = dedup(persons) print(unique_persons) for person in unique_persons: print(person)
Output:[<__main__.Person instance at 0x02FD1E40>, <__main__.Person instance at 0x02FD53A0>, <__main__.Person instance at 0x02FD53C8>]
John
Allice
John
[<__main__.Person instance at 0x02FD1E40>, <__main__.Person instance at 0x02FD53A0>]
John
Allice
>>>
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs