Organizing list of tuples
<p>I have a list of tuples which I create dynamically.</p>

<p>The list appears as:</p>

<pre><code>List = [(1,4), (8,10), (19,25), (10,13), (14,16), (25,30)]
</code></pre>

<p>Each tuple <code>(a, b)</code> of list represents the range of indexes from a certain table.</p>

<p>The ranges <code>(a, b) and (b, d)</code> is same in my situation as <code>(a, d)</code></p>

<p>I want to merge the tuples where the 2nd element matches the first of any other.</p>

<p>So, in the example above, I want to merge <code>(8, 10), (10,13)</code> to obtain <code>(8,13)</code> and remove <code>(8, 10), (10,13)</code></p>

<p><code>(19,25) and (25,30)</code> merge should yield <code>(19, 30)</code></p>

<p>I don't have a clue where to start. The tuples are non overlapping.</p>

<p>Edit: I have been trying to just avoid any kind of for loop as I have a pretty large list</p>

<p>Here is one optimized recursion approach:</p>

<pre><code>In [44]: def find_intersection(m_list):
             for i, (v1, v2) in enumerate(m_list):
                 for j, (k1, k2) in enumerate(m_list[i + 1:], i + 1):
                     if v2 == k1:
                         m_list[i] = (v1, m_list.pop(j)[1])
                         return find_intersection(m_list)
             return m_list
</code></pre>

<p>Demo:</p>

<pre><code>In [45]: lst = [(1,4), (8,10), (19,25), (10,13), (14,16), (25,30)]

In [46]: find_intersection(lst)
Out[46]: [(1, 4), (8, 13), (19, 30), (14, 16)]
</code></pre>

python algorithm list tuples