Search code examples
pythonlistsortingskip

How to sort python list by keeping some elements in the end


I want to sort list of countries based on continents, but want to keep 'Rest of Asia' and 'Rest of America' at the end. How can we modify the sort function

A = ['China', 'India', 'Brazil', 'Canada', 'Rest of Asia', 'Rest of America', 'USA', 'UAE', 'Sri Lanka']
sorted(A)

I want to have the result where Rest of America and Rest of Asia should come in the end

like: ['China', 'India', 'Brazil', 'Canada', 'USA', 'UAE', 'Sri Lanka', 'Rest of Asia','Rest of America']


Solution

  • If all you want is the results starting with Rest at the end, you can use a custom sorter:

    A = ['China', 'India', 'Brazil', 'Canada', 'Rest of Asia', 'Rest of America', 'USA', 'UAE', 'Sri Lanka']
    
    def mySort(a):
        if a.startswith('Rest'):
            return 1
        return 0
    
    A.sort(key=mySort)
    
    Out[1]:
    ['China',
     'India',
     'Brazil',
     'Canada',
     'USA',
     'UAE',
     'Sri Lanka',
     'Rest of Asia',
     'Rest of America']
    

    Or a simpler version with the anonymous call:

    A.sort(key=lambda x: x.startswith('Rest'))