One method is to create tuples of the indices and length before sorting, then reducing to the original input after. Below is one such example of doing this. Note that if the index is not found, we assume that it should come at the end and then just be sorted by length.
def sortby_index_length(input, items):
def index_or_large(haystack, needle):
try:
return haystack.index(needle)
except ValueError:
return len(haystack)
indexes = list(map(lambda x: (x, index_or_large(input, x)), items))
indexes.sort(key=lambda xy: (xy[1], len(xy[0])))
return list(map(lambda x: x[0], indexes))
print(sortby_index_length("CCB", ['C','C','B','CC']))
Which gives the expected output of ['C', 'C', 'CC', 'B']. This also uses the sort function where we specify the sorting ordering to be index tie broken by length.