Reputation: 55
I'm a relatively new python programmer and am trying to fix my contains method in my ArrayList class. I want to check if an input value is actually contained in the stored list.
def __contains__(self, value):
"""Implements `val in self`. Returns true if value is found in this list."""
for num in iter(self):
if(num==value):
return True
else:
return False
Could someone tell me what might be wrong with this code? I test it with a generated list range(100) for the value 50 but it won't return True.
Upvotes: 0
Views: 59
Reputation: 36033
This tests if num
is equal to the first value in self
. You should only return False
after the whole loop ends and you've shown that num
wasn't equal to anything in the list since you haven't returned True
yet.
Also note that the iter
is implied if you just write for num in self
. And a normal Python list ([]
) is essentially a Java ArrayList
already.
Upvotes: 1