Ord() in sorting.

NdoriaNdoria
2 min read

Using ord() as a key in python - sorting.

Well, it's not as hard or complicated as you may think. I thought the same, probably many others too - but don't worry. Here's how to use ord() as your key during sorting:

  • create your main function that takes in the list you want to sort,
    here i will use <list_to_sort> as my parameter.

  •   list_to_sort = []
    
      def to_sort(list_to_sort):
    
  • Next, we are going to grab the ordinal(ord) for each value in the string to use it later in our sort. Remember, keys cannot be objects such as int or strings:

def to_sort(list_to_sort):

    def ordinal_key(list_to_sort):
        return ( ord(c) for c in list_to_sort )
As seen above, we use for loop to iterate through our list and call ord() on each value in our string
  • Now that we have a well-defined key waiting to be called, let's sort our list:
def to_sort(list_to_sort):

    def ordinal_key(list_to_sort):
        return ( ord(c) for c in list_to_sort )

    list_to_sort.sort( key = ordinal_key )

    print(list_to_sort)    # to display results

to_sort()     # call function for results
  • Alternatively, if you are having trouble defining a function within a function, or you want to be more direct in your approach , you can try this:

  •   list_to_sort = []
    
      def ordinal_key(list_to_sort):
          return ( ord(c) for c in list_to_sort )
    
      def to_sort(list_to_sort):  
          list_to_sort.sort( key = ordinal_key )
              return list_to_sort
    

Tell me if this works for you too!

0
Subscribe to my newsletter

Read articles from Ndoria directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ndoria
Ndoria