DaCard
DaCard

Reputation: 651

How to remove a class object from a python list?

Assume that I have a class (Base) & a list (obj)

class Base:
    def __init__(self, x, y):
        self.x = x 
        self.y = y 

    def __repr__(self):
        return f"Base({self.x}, {self.y})"

    def area(self):
        return self.x*self.y

obj = [Base(10, 12), Base(2, 5), Base(7, 8)]

How to remove Base(2, 5) from the obj list? The obj.remove(Base(2,5)) does not work. Any Suggestions?

Upvotes: 1

Views: 466

Answers (2)

Prune
Prune

Reputation: 77910

Your immediate problem is that you do not have an element called Base(2, 5) in that list: you have three object descriptors. Your call to remove does not refer to any of those three elements: it refers to a fourth element. Yes, that element happens to have the same attributes as one list element, but you have not implemented the equality operator for Base to recognize that coincidence.

The brute-force way is to iterate through the list and find the corresponding element:

for elem in obj:
    if (elem.x, elem.y) == (2, 5):
        obj.remove(elem)
        break

Upvotes: 3

hiro protagonist
hiro protagonist

Reputation: 46921

list.remove needs to be able to tell when the element to be removed is the same as one of the elements in the list.

so you could implement an __eq__ method along those lines:

class Base:    
    def __eq__(self, other):
        if not isinstance(other, Base):
            return NotImplemented
        return self.x, self.y == other.x, other.y

and obj.remove(Base(2,5)) will work.

Upvotes: 7

Related Questions