title: How to search objects in Python List using __contains__ / "in" keyword?
body: <p>I would like to make a list of objects which I define, then use the <code>in</code> keyword (which calls <a href="https://docs.python.org/2/reference/datamodel.html#object.__contains__" rel="nofollow noreferrer"><code>__contains__</code></a>) to determine if said object exists in the Python list.</p>
  <p>Here is a minimal example with comments:</p>
  <pre><code>&gt;&gt;&gt; class Foo(object):
  ...     def __init__(self, name):
  ...             self.name = name
  ...     def __contains__(self, item):
  ...             return self.name == item
  ... 
  &gt;&gt;&gt; list_of_objects = [Foo(&quot;bar&quot;), Foo(&quot;baz&quot;), Foo(&quot;quux&quot;)]
  &gt;&gt;&gt; # I want to see if &quot;bar&quot; is in this list of Foo() objects
  &gt;&gt;&gt; Foo(&quot;bar&quot;) in list_of_objects
  False      # &lt;-- I want this to be True
  </code></pre>
  <p>Shouldn't the <code>in</code> keyword iterate over the Python list and use the <code>__contains__</code> method to determine existence of the object?</p>
  <p>Extra kudos if calls to lists <code>index()</code> function are also operational.</p>
  <h1>Update</h1>
  <p>Thanks to @user2357112, Looks like the answer is implementing the equivalence operator <a href="https://docs.python.org/3/reference/datamodel.html#object.__eq__" rel="nofollow noreferrer"><code>__eq__</code></a>. Adding the following bit to the <code>Foo</code> class in the previous example fixes the issues I was having.</p>
  <pre><code>&gt;&gt;&gt; class Foo(object):
  ...     def __init__(self, name):
  ...             self.name = name
  ...     def __eq__(self, other):
  ...             return other.name == self.name
  &gt;&gt;&gt; list_of_objects = [Foo(&quot;bar&quot;), Foo(&quot;baz&quot;), Foo(&quot;quux&quot;)]
  &gt;&gt;&gt; Foo(&quot;bar&quot;) in list_of_objects
  True
  </code></pre>