Shade
Shade

Reputation: 33

Is there a way to delete an object in list by value?

the 'list.remove' function does not compare objects by value

suppose the code is:

class item:
def __init__(self, a, b):
    self.feild1 = a
    self.field2 = b

a = item(1,4)
b = item(1,4)
l = [a]
l.remove(b) # doesn't remove l[0]

Upvotes: 1

Views: 50

Answers (1)

Patrick Haugh
Patrick Haugh

Reputation: 61042

Because you don't provide a __eq__ implementation, your class inherits the method from object. object.__eq__ doesn't compare the values of attribute, it just checks to see that id(a) == id(b). You need to write your own __eq__:

class item:
    def __init__(self, a, b):
        self.field1 = a
        self.field2 = b
    def __eq__(self, other):
        if not isinstance(other, item):
            return NotImplemented
        return self.field1 == other.field1 and self.field2 == other.field2

a = item(1,4)
b = item(1,4)
l = [a]
l.remove(b)

print(l)
# []

Upvotes: 4

Related Questions