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 following should work.  It breaks tuples into individual numbers, then finds the tuple bound on each cluster.  This should work even with difficult overlaps, like <code>[(4, 10), (9, 12)]</code></p>

<p>It's a very simple fix.</p>

<pre><code># First turn your list of tuples into a list of numbers:
my_list = []
for item in List: my_list = my_list + [i for i in range(item[0], item[1]+1)]

# Then create tuple pairs:
output = []
a = False
for x in range(max(my_list)+1):
    if (not a) and (x in my_list): a = x
    if (a) and (x+1 not in my_list):
        output.append((a, x))
        a = False

print output
</code></pre>

python algorithm list tuples