If your objects are of primitive types, you can use set
list(set(test_clist))
and if not, like your case then you have 2 solutions
1- Implement __hash__() & __eq__()
You have to implement __hash__() & __eq__ in your class in order to use set() to remove the duplicates
see below example
class MyClass(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"MyClass({self.x} - {self.y})"
def __hash__(self):
return hash((self.x, self.y))
def __eq__(self, other):
if self.__class__ != other.__class__:
return NotImplemented
return (
self.x == other.x and
self.y == other.y
)
l = []
l.append(MyClass('hello', 'world'))
l.append(MyClass('hello', 'world'))
l.append(MyClass('', 'world'))
l.append(MyClass(None, 'world'))
print(list(set(l)))
Since you have more than one key that you want to use in comparing, __hash__() uses a key tuple.
__repr__() just for representing the class's object as a string.
2- Use 3rd Party Package
check out a package called toolz
then use unique() method to remove the duplicates by passing a key
toolz.unique(test_list, key=lambda x: x.your_attribute)
In your case, you have more than one attribute, so you can combine them into one, for example by creating a concatenated property for them then pass it to toolz.unique() as your key, or just concatenate them on the fly like below
toolz.unique(test_list, key=lambda x: x.first_attribute + x.second_attribute)
list(set(test_clist))set cannot have duplicates and are often used to remove themhashable, that means you need to implement__hash__(self)and__eq__(self, other)methods