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>The list is first sorted and adjacent pairs of (min1, max1), (min2, max2) are merged together if they overlap.</p>

<pre><code>MIN=0
MAX=1

def normalize(intervals):
    isort = sorted(intervals)
    for i in range(len(isort) - 1): 
        if isort[i][MAX] &gt;= isort[i + 1][MIN]:
            vmin = isort[i][MIN]
            vmax = max(isort[i][MAX], isort[i + 1][MAX])
            isort[i] = None
            isort[i + 1] = (vmin, vmax)
    return [r for r in isort if r is not None]

List1 = [(1,4), (8,10), (19,25), (10,13), (14,16), (25,30)]
List2 = [(1, 4), (4, 8), (8, 10)]
print(normalize(List1))
print(normalize(List2))

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

python algorithm list tuples