How to Custom Sort a Python String List

If you have a list of string items and you want to perform a custom sort order (ie not alphabetical), you can use the key parameter in the list.sort() method to define the order.

fruits = ['apple','orange','banana','pear','mango']

sort_order = ['pear','mango','kiwi','grape','orange','banana','apple']

fruits.sort(key=sort_order.index)

The resulting list will now be sorted: ['pear', 'mango', 'orange', 'banana', 'apple']

The sort_order variable can include more items than what is in your target list. This is helpful because you can have your sort order list variable be inclusive of any items from multiple lists.


Posted

in

by

Tags: