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>non-recursive approach, using sorting (I've added more nodes to handle complex case):</p>

<pre><code>l = [(1,4), (8,10), (19,25), (10,13), (14,16), (25,30), (30,34), (38,40)]
l = sorted(l)

r=[]
idx=0

while idx&lt;len(l):
    local=idx+1
    previous_value = l[idx][1]
    # search longest string
    while local&lt;len(l):
        if l[local][0]!=previous_value:
            break
        previous_value = l[local][1]
        local+=1
    # store tuple
    r.append((l[idx][0],l[local-1][1]))
    idx = local


print(r)
</code></pre>

<p>result:</p>

<pre><code>[(1, 4), (8, 13), (14, 16), (19, 34), (38, 40)]
</code></pre>

<p>The only drawback is that original sort order is not preserved. I don't know if it's a problem.</p>

python algorithm list tuples