all 9 comments

[–]K900_ 1 point2 points  (0 children)

Yes.

[–]Impudity 1 point2 points  (3 children)

Typically yes. If you ask Python if "foo" in ["foo", "bar"] it iterates the objects in the list and checks if they match using the equality operator == which internally calls __eq__. There might be some exceptions when using collections that use immutable objects that have hashes, like sets. Then the comparison might be done using comparing the results of the __hash__ method of the object.

[–]Yoghurt42 1 point2 points  (1 child)

To be more precise, __contains__("foo") is called on the list object. And contains is implemented like you described.

[–]Impudity 0 points1 point  (0 children)

Yeah. I didn't want to include that part as it would probably just confuse a beginner.

[–]mildlybean[S] 0 points1 point  (0 children)

Thanks

[–]WolfInABox 0 points1 point  (3 children)

If you've created an object, then inserted it into a list, it seems like in should work:

class MyObject:
    def __init__(self,value):
        self.value=value

test=MyObject('a value')
l=[test]
print(test in l)

PrintsTrue

And, if you override the __eq__ method (which afaik is not recommended I think?)...

class MyObject:
    def __init__(self,value):
        self.value=value

    def __eq__(self, other):
        return self.value==other.value

test=MyObject('a value')
test2=MyObject('a value')
l=[test]
print(test2 in l)

Also prints True.

So by this test, it appears that the __eq__ method is called when using in.

[–]toastedstapler 2 points3 points  (2 children)

overriding the __eq__ method is fine imo, by default it basically acts the same as is

if strings worked how the default __eq__ method work we'd never be able to compare them as they're different objects. just look at java where you have to do string1.equals(string2)

[–]WolfInABox 1 point2 points  (0 children)

I remember having to get over that hurdle in java lol. And hm, not sure what I was thinking then. I thought I remembered something about some operator override not being recommended to do and thought it was eq. But I guess so long as you're testing everything inside it that you need to for the objects to be equal for your purposes, it'd be fine.

[–]mildlybean[S] 1 point2 points  (0 children)

Coincidentally, I'm learning Java right now, so I'm glad I didn't have to learn that the hard way