Sorting a list to by another's order

Mark McEahern marklists at
Fri Aug 30 15:42:48 CEST 2002

[Graeme Longman]
> I have two lists:
> listA = ['d', 'c', 'f', 'a', 'b', 'e']
> listB = ['a', 'c', 'd', 'f']
> I need to sort listA so that it's order corresponds to that of listB (if
> the item in listA isn't in listB then it should be at the end of the
> list)
> Is there a quick way to do this using sort() instead of writng a bunch
> of for loops and if-else statements ?

This relies on nested scopes:

def make_sort_by_list(list_with_order):
    def sort_by_list(x, y):
            order_of_x = list_with_order.index(x)
            order_of_y = list_with_order.index(y)
            return cmp(order_of_x, order_of_y)
        except ValueError:
            # Not found--stick it at the end.
            return 1
    return sort_by_list

listA = ['d', 'c', 'f', 'a', 'b', 'e']
listB = ['a', 'c', 'd', 'f']

sort_by = make_sort_by_list(listB)

print listA
expectedOrder = ['a', 'c', 'd', 'f', 'b', 'e']
assert listA == expectedOrder


More information about the Python-list mailing list