def get_matching_prefixes(iterable, is_sorted=False):
    """Get tuples of terms from `iterable` where one term is prefix of
    another term.

    The tuples will contain the prefix and exactly one prefixed term::

       >>> list(get_matching_prefixes(["a", "b", "aa"]))
       [('a', 'aa')]

    For terms that prefix more than one other term, one tuple is
    returned for each of the prefixed terms::

       >>> list(get_matching_prefixes(["a", "aa", "ab"]))
       [('a', 'aa'), ('a', 'ab')]

    The `is_sorted` parameter is a hint telling, whether the given
    `iterable` is already sorted or not. If it is, we do not resort
    the iterable and can compute results much faster.

    Results are undefined - and most probably broken -, if `is_sorted`
    is ``True`` while in fact the `iterable` is unsorted.

    This function is not destructive, which means that iterables
    passed-in will not be changed.

    """
    elems = iterable[:]
    if not is_sorted:
        elems.sort()
    while len(elems) > 1:
        idx = 1
        while elems[0] and elems[idx].startswith(elems[0]):
            yield elems[0], elems[idx]
            idx += 1
            if idx == len(elems):
                break
        elems.pop(0)
