Get intersection of list elements with different sublist datatypes
<p>I have two lists, which contains list elements, e.g:</p>

<pre><code>list1 = [['placeholder1', {'data': 'data1'}], ['placeholder2', {'data': 'data2'}], ['placeholder2', {'data': 'data1'}]]
list2 = [['placeholder2', {'data': 'data2'}], ['placeholder3', {'data': 'data5'}]]

intersection_result = [['placeholder2', {'data': 'data2'}]]
</code></pre>

<p>The structure of the sub-list elements is just an example. It can also happen that all the sub-list elements contains strings <code>['asdf', 'qwert']</code> or a mixture of string and numbers <code>['sdfs', 232]</code>. However, the sub-list structure is always the same (in both lists).</p>

<p>How can I get the intersection of lists elements which are identical in both lists?</p>

<p>If my understanding is correct, you can get the intersection by checking and selecting <a href="https://docs.python.org/3/library/functions.html#any" rel="nofollow"><code>any()</code></a> of the elements in the smallest list which are equal to ones in the larger one.</p>

<p>With a comprehension, this would look like this:</p>

<pre><code>intersection_res = [l for l in min(list2, list1, key=len) if any(l == l2 for l2 in max(list1, list2, key=len))]
</code></pre>

<p>This uses, <a href="https://docs.python.org/3/library/functions.html#min" rel="nofollow"><code>min</code></a> and <a href="https://docs.python.org/3/library/functions.html#max" rel="nofollow"><code>max</code></a> with a key assigned to <a href="https://docs.python.org/3/library/functions.html#len" rel="nofollow"><code>len</code></a> to always select from the smaller list and check against the larger one.</p>

<p>This yields:</p>

<pre><code>print(intersection_res)
[['placeholder2', {'data': 'data2'}]]
</code></pre>

<p>This comprehension can be trimmed down if you pre-assign the min-max lists or, of course, if you are always certain which list is larger than the other:</p>

<pre><code>sm, la = list1, list2 if len(list1) &lt; len(list2) else list2, list1
intersection_res = [l for l in sm if any(l == l2 for l2 in la)]
</code></pre>

python list python-3.x intersection python-3.5