def dedupe_and_sort(sequence, first=None, last=None):
    """
    De-dupe and partially sort a sequence.

    The `first` argument should contain all the items that might appear in
    `sequence` and for which the order (relative to each other) is important.

    The `last` argument is the same, but matching items will be placed at the
    end of the sequence.

    For example, `INSTALLED_APPS` and `MIDDLEWARE_CLASSES` settings.

    Items from `first` will only be included if they also appear in `sequence`.

    Items from `sequence` that don't appear in `first` will come
    after any that do, and retain their existing order.

    Returns a sequence of the same type as given.
    """
    first = first or []
    last = last or []
    # Add items that should be sorted first.
    new_sequence = [i for i in first if i in sequence]
    # Add remaining items in their current order, ignoring duplicates and items
    # that should be sorted last.
    for item in sequence:
        if item not in new_sequence and item not in last:
            new_sequence.append(item)
    # Add items that should be sorted last.
    new_sequence.extend([i for i in last if i in sequence])
    # Return a sequence of the same type as given.
    return type(sequence)(new_sequence)
def dedupe_and_sort ( sequence , first = None , last = None ) : first = first or [ ] last = last or [ ] new_sequence = [ i for i in first if i in sequence ] for item in sequence : if item not in new_sequence and item not in last : new_sequence . append ( item ) new_sequence . extend ( [ i for i in last if i in sequence ] ) return type ( sequence ) ( new_sequence )
De-dupe and partially sort a sequence.

    The `first` argument should contain all the items that might appear in
    `sequence` and for which the order (relative to each other) is important.

    The `last` argument is the same, but matching items will be placed at the
    end of the sequence.

    For example, `INSTALLED_APPS` and `MIDDLEWARE_CLASSES` settings.

    Items from `first` will only be included if they also appear in `sequence`.

    Items from `sequence` that don't appear in `first` will come
    after any that do, and retain their existing order.

    Returns a sequence of the same type as given.