This is happening because what you understand as identifying features of two instances of your Node
class, is not how python understands it.
The problem lies here. Suppose you asked python 5==5
, python would return True
. This is because python knows about int
s. However, Node
is a custom class that you defined, so you need to tell python when two Node
objects are the same. Since you (probably) haven't, python defaults to comparing their locations in memory. Since two separate instances will be in two different memory locations, python will return False
. If you are familiar with Java at all, this is like the difference between ==
and .equals(...)
In order to do this, go into your Node
class and define the __eq__(self, other)
method, where other
is expected to be another instance of Node
.
For example, if your nodes have an attribute called name
and two nodes that have the same name are considered to be the same, then your __eq__
could look like this:
def __eq__(self, other):
myName = self.name
hisName = other.name
if myName == hisName:
return True
else:
return False
Of course, the more elegant way of writing that same function is:
def __eq__(self, other):
return self.name == other.name
When this is done, your error should disappear
EDIT 1: In response to DSM's comment
class Node: pass
a = [Node(), Node()]
b = a[:]
b.remove(a.pop(0))
This will work. But upon closer inspection, it becomes evident that a[0] and b[0] are in fact the same object. This can be verified by calling id(a[0])
and comparing it with id(b[[0])
to confirm that they are indeed the same
EDIT 2: In response to the OP's follow up question (added to the original question as edit)
Yes, the object not existing in the list will cause an error which would normally stop program flow. This can be solved in either of the following two ways:
if x in my_list:
my_list.remove(x)
OR
try:
my_list.remove(x)
except:
pass
The second method attempts to remove x
from my_list
and if that results in an error, ignores the error