Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find object in a python list using the 'in' operator

Is it possible to do something that looks like this:

if obj in a_list_of_the_same_obj_type:
     #do stuff

My obj already have the __eq__ and __ne__ function that compare on an attribute so I thought the in keyword would call it but it doesn't look like it does.

like image 343
Some Guy Avatar asked Sep 13 '25 12:09

Some Guy


2 Answers

In this case, operator 'in' calls the __contains__() of python´s built-in list object which then calls the __eq__() of your object, so make sure that the __eq__() dunder method in your obj-class is properly implemented.

like image 96
Branko Dosenovic Avatar answered Sep 15 '25 03:09

Branko Dosenovic


You need to implement __contains__ to be able to test for membership

like image 33
Slam Avatar answered Sep 15 '25 01:09

Slam