Intersection of 2 lists which contain non-hashables
<p>What is the most efficient way to find the intersection of 2 lists when both lists contain non-hashables?</p>

<p>Basically, let's say I have the following lists (which I completely made up):</p>

<pre><code>A = [&lt;foo.bar object at 0x7f267c664080&gt;, &lt;foo.bar object at 0x7f267c664099&gt;]
B = [&lt;foo.bar object at 0x7f267c664080&gt;, &lt;foo.bar object at 0x123456789101&gt;]
</code></pre>

<p>We can see that the first element of <code>A</code> is the same as the first element of <code>B</code>. </p>

<p>I can do the simple thing by creating a for loop:</p>

<pre><code>intersection = []

for obj_a in A:
    for obj_b in B:
        if ( (obj_a == obj_b) and (obj_a not in intersection) ):
            intersection.extend(obj_a)
</code></pre>

<p>but I'm just wondering if there is a more efficient, cooler, or simpler way. For example, there is:</p>

<pre><code>C = [1, 2, 3]
D = [3, 4, 5]
set(C).intersection(set(D))
</code></pre>

<p>...but obviously I can't use <code>set</code> or <code>frozenset</code> for non-hashables because I get</p>

<pre><code>TypeError: unhashable type: foo.bar
</code></pre>

<p>Is there anything like this for non-hashables?</p>

<p>A simple solution using list comprehension: <code>intersection = [element for element in A if element in B</code> checks if two elements of the same <em>value</em> are there. For example, for <code>[1, 2, 3]</code> and <code>[0, 1, 5]</code>, it will return <code>[1]</code>.</p>

python