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>If they don't overlap, then you can sort them, and then just combine adjacent ones.</p>

<p>Here's a generator that yields the new tuples:</p>

<pre><code>def combine_ranges(L):
    L = sorted(L)  # Make a copy as we're going to remove items!
    while L:
        start, end = L.pop(0)  # Get the first item
        while L and L[0][0] == end:
            # While the first of the rest connects to it, adjust
            # the end and remove the first of the rest
            _, end = L.pop(0)
        yield (start, end)

print(list(combine_ranges(List)))
</code></pre>

<p>If speed is important, use a <code>collections.deque</code> instead of a list, so that the <code>.pop(0)</code> operations can be in constant speed.</p>

python algorithm list tuples