Compare items in list if tuples Python
<p>If have this list of tuples:</p>

<pre><code>l1 = [('aa', 1),('de', 1),('ac', 3),('ab', 2),('de', 2),('bc', 4)]
</code></pre>

<p>I want to loop over it, and check if the second item in each tuple is the same as another second item in a tuple in this list. If it is, I want to put this tuple in a new list of tuples.</p>

<p>So from this list of tuples I would expect for my new list of tuples:</p>

<pre><code>l2 = [('aa', 1), ('de', 1), ('ab', 2),('de', 2)]
</code></pre>

<p>Because the one's and the two's match. Right now if have this:</p>

<pre><code>l2 = []
for i in range(len(l1)):
    if l1[i][1] in l1[:][0]:
        l2.append(l1[i])
</code></pre>

<p>However, this only gives me:</p>

<pre><code>l2 = [('aa', 1), ('de', 1)]
</code></pre>

<p>I'm pretty sure I'm not indexing the list of tuples right. The solution is probably pretty simple, but I'm just not getting there. </p>

<p>You'll need two passes: one to count how many times the second element exists, and another to then build the new list based on those counts:</p>

<pre><code>from collections import Counter

counts = Counter(id_ for s, id_ in l1)
l2 = [(s, id_) for s, id_ in l1 if counts[id_] &gt; 1]
</code></pre>

<p>Demo:</p>

<pre><code>&gt;&gt;&gt; from collections import Counter
&gt;&gt;&gt; l1 = [('aa', 1),('de', 1),('ac', 3),('ab', 2),('de', 2),('bc', 4)]
&gt;&gt;&gt; counts = Counter(id_ for s, id_ in l1)
&gt;&gt;&gt; [(s, id_) for s, id_ in l1 if counts[id_] &gt; 1]
[('aa', 1), ('de', 1), ('ab', 2), ('de', 2)]
</code></pre>

<p>Your code goes wrong with <code>l1[:][0]</code>; <code>l1[:]</code> just creates a <em>shallow copy</em> of the list, then takes the first element from that list. Even if it worked, your approach would have to check <em>every other element in your list</em> for every tuple you consider, which is really inefficient (the code would take N**2 steps for a list of N tuples).</p>

python python-2.7