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?
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)]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With