I have an object a and a list, and i want to check if the object a is in that list. That means the same object with the same id. To compare a and a single item of that list i would us the is keyword, something like a is ls[0], not == because == would compare the values of the two and not if they are the same object. I know about the in keyword to see if a list contains a value but that compares values (similar to ==) and not objects.
Consider the following code:
class Foo(object):
def __init__(self,value):
self.value=value
def __eq__(self,other):
return True
a=Foo(0)
b=Foo(1)
if a is b:
print("Error, a is b")
exit()
ls=[b]
if b is not ls[0]:
print("Error, b is not ls[0]")
exit()
if a in ls:
print("Don't print this line")
else:
print("Print this line instead")
How can i change the if statement so that "Print this line instead" is printed?
Changing it to if a is in ls: or if a in is ls: gives a syntax error. And yes i know i can make a function like this:
def isIn(object,ls):
for e in ls:
if e is object:
return True
return False
But that looks clumsy, is there a nicer way?