Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can't remove a class object from a list

Tags:

python

list

So I have this list (Sheep is a class i created, requiring one parameter):

list = [Sheep(2), Sheep(3), Sheep(3), Sheep(4), Sheep(4), Sheep(4), Sheep(5), Sheep(5), Sheep(5), Sheep(5), Sheep(6), Sheep(6), Sheep(6), Sheep(7), Sheep(7), Sheep(8)]

However, when I try to remove Sheep(2) (list.remove(Sheep(2)) from the list, it returns ValueError: list.remove(x): x not in list

How do I fix this?

like image 581
Ewokyeyey Avatar asked Sep 02 '25 02:09

Ewokyeyey


2 Answers

To test for membership in a python list with a custom class you must provide an equality (__eq__) method

class Sheep:

    def __init__(self, x):
        self.x = x

    def __eq__(self, other):
        assert isinstance(other, Sheep)
        return self.x == other.x

Now you can create instances of your class with the same "x" and they will be members of your list

foo = [Sheep(2), Sheep(3), Sheep(3), Sheep(4), Sheep(4), Sheep(4), Sheep(5), Sheep(5), Sheep(5), Sheep(5), Sheep(6), Sheep(6), Sheep(6), Sheep(7), Sheep(7), Sheep(8)]
print(Sheep(2) in foo)  # True

And you should be able to remove them too

foo.remove(Sheep(2))
print(foo)  # [Sheep(3), Sheep(3), Sheep(4), Sheep(4), Sheep(4), Sheep(5), Sheep(5), Sheep(5), Sheep(5), Sheep(6), Sheep(6), Sheep(6), Sheep(7), Sheep(7), Sheep(8)]
like image 113
Iain Shelvington Avatar answered Sep 05 '25 15:09

Iain Shelvington


The two Sheep(2)s are different objects.

To let the the first Sheep(2) be found by comparing it to the second one, define equality on your Sheep. Then

class Sheep: 
    def __init__(self, camouflage_score): 
       self.camo = camouflage_score          

    def __eq__(self, other):
        return other and self.camo == other.camo
like image 37
Joshua Fox Avatar answered Sep 05 '25 15:09

Joshua Fox