Python sort

How to use the sort function with practical examples. In Python, we can use this function to sort objects like Lists, dictionaries, Tuples, Sets, and Strings in reverse, and it is one of the most commonly asked questions.

In Python programming, we have functions to organize the objects, and they are the sort that works only on list items and uses sorted for the remaining objects. The syntax of these functions are

# List Items using Functions in Reverse
list_Name.sort(reverse = True, key = Function_Name) # 1x

# Reverse using Functions
sorted(Object_Name, reverse = True, key = Function_Name) # 2

From the above Python sort syntax, if you observe statements 1 and 2

  1. Both the reverse and the key arguments and their values are optional. So, you can use either one of them, both, or none. Here, the Python sort reverse argument is to arrange the elements in Reverse or Descending Order. Next, Function_name is to pass the name to it.
  2. This method accepts Object_Name as the mandatory argument. Here also, both the reverse and the key arguments and their values are optional.

Here, Function_Name can be any user-defined. Or you can use Python built-in methods like len, min, max, etc.

Python sort List Items Examples

How do you sort the List items in ascending & descending order using this Python list function?

This Python list function works on list items to sort them in ascending. In this example, first, we declared an integer list. Next, we used this method to organize the integer and string lists in ascending. Here, this method uses alphabetical order for the string list.

TIP: Please refer to the List method article to learn about this method on List items.

listexample = [13, 98, 45, 125, 6, 22, 9, 78]
print(listexample)

listexample.sort()
print( listexample)

liststring = ['orange', 'banana', 'kiwi', 'grape', 'blackberry']
print(liststring)

liststring.sort()
print(liststring)

[13, 98, 45, 125, 6, 22, 9, 78]
[6, 9, 13, 22, 45, 78, 98, 125]

['orange', 'banana', 'kiwi', 'grape', 'blackberry']
['banana', 'blackberry', 'grape', 'kiwi', 'orange']

Python Sort String List in Reverse

The sort function contains an argument called reverse = True. It allows us to arrange the list of items in descending order. Here, we are using the reverse = true. It means string list items are sorted in Descending.

liststring = ['orange', 'blackberry', 'kiwi', 'grape', 'banana']
print("\nOriginal List String = ", liststring)

liststring.sort(reverse = True)
print("Result String List = ", liststring)
Original List String =  ['orange', 'blackberry', 'kiwi', 'grape', 'banana']
Result String List =  ['orange', 'kiwi', 'grape', 'blackberry', 'banana']

Python list sort with key argument Example

This List method has another argument called a key. This key accepts any Python function, and that one determines the sorting factor.

In this example, we created a secondValue function. It returns the second argument from the nested list. Next, we are using this method as the key value. It means the list example is arranged based on the second value in the nested list.

In the next lines of code, we used the reverse and key arguments. It means Python list items sorted in ascending and descending based on the second value in the nested list.

def secondValue(value):
    return value[1]

listexample = [[17, 222], [222, 13], [14, 151], [99, 77]]
print("\n Original List = ", listexample)

# List in Ascending using Second item
listexample.sort(key = secondValue)
print("Asc using Second = ", listexample)

# List in Descending using Second item
listexample.sort(reverse = True, key = secondValue)
print("Descending List = ", listexample)

 Original List =  [[17, 222], [222, 13], [14, 151], [99, 77]]

Asc using Second =  [[222, 13], [99, 77], [14, 151], [17, 222]]

Descending List =  [[17, 222], [14, 151], [99, 77], [222, 13]]

Sort Tuple in Python Examples

The following code shows how to sort Tuple items in ascending and descending. The below code organizes the elements in an integer tuple.

Python Sort Example 4

Python Sort Tuple Reverse Example 2

In this, first, we declared a string tuple. Next, we used the function to sort them in ascending. Here, it uses alphabetical order for string tuples.

The Python sorted function uses its argument called a reverse to organize the tuple items in descending. The below code arranges the string tuple elements in Descending.

tupleexample = ('orange', 'banana', 'kiwi', 'grape', 'blackberry')
print("\n Original Tuple = ", tupleexample)

# Tuple
descExm = sorted(tupleexample, reverse = True)
print("Descending Tuple = ", descExm)

Original Tuple =  ('orange', 'banana', 'kiwi', 'grape', 'blackberry')
Descending Tuple =  ['orange', 'kiwi', 'grape', 'blackberry', 'banana']

This Python sort tuple function has another argument called a key. This key argument accepts any method and determines the sorting factor. In this example, we created a function to find the length of a string.

We used this length method as the key value. It means tuple items are sorted based on the length in the ascending. Next, we used the reverse along with this key argument. It organizes the tuple items in descending using their length.

def length(item):
    return len(item)

tupleexample = ('orange', 'kiwi', 'grape', 'blackberry')
print("\n Original Tuple = ", tupleexample)

ascEx = sorted(tupleexample, key = length)
print("Tuple by Length = ", ascEx)

# Tuple
descEx = sorted(tupleexample, reverse = True, key = length)
print("Descending Tuple by Length = ", descEx)

tuple items output


 Original Tuple =  ('orange', 'kiwi', 'grape', 'blackberry')
Tuple by Length =  ['kiwi', 'grape', 'orange', 'blackberry']
Descending Tuple by Length =  ['blackberry', 'orange', 'grape', 'kiwi']

Tuple sorted with reverse and key arguments

Python allows you to use any built-in functions as the sort key argument. This tuple example is the same as the above. However, we are using the len as the key argument. It means the user-defined length replaces the len method.

tupleexm1 = ('orange', 'kiwi', 'grape', 'blackberry')
print("\n Original Tuple = ", tupleexm1)

# Tuple
descExm = sorted(tupleexm1, reverse = True, key = len)
print("Descending Tuple by Length = ", descExm)

 Original Tuple =  ('orange', 'kiwi', 'grape', 'blackberry')
Descending Tuple by Length =  ['blackberry', 'orange', 'grape', 'kiwi']

Python Sorted Set Examples

The following examples show how to sort set items in ascending and descending.

This Python function is the one that you can use to sort the set items in ascending and descending.

In this set example, we first declared a set of positive and negative values. Next, we used this method to arrange them in ascending. Lastly, we used the set function and the reverse argument to arrange sets in descending order.

setExample = {22, -15, 17, 0, 12, -4, 7, 10}
print("\n Original Set = ", setExample)

print("\nAscending Set = ", sorted(setExample))

descSet = sorted(setExample, reverse = True)
print("Descending = ", descSet)

 Original Set =  {0, 7, 10, 12, -15, 17, 22, -4}

Ascending Set =  [-15, -4, 0, 7, 10, 12, 17, 22]
Descending =  [22, 17, 12, 10, 7, 0, -4, -15]

Python Sorted Set in Reverse Example

In this example, we use this function on the set of string values — the below code sorts the string set in reverse or descending.

setStringExample = {'mango', 'kiwi', 'apple', 'orange', 'banana'}
print("\n Original Set = ", setStringExample)

descStrSet = sorted(setStringExample, reverse = True)
print("Set in Descending = ", descStrSet)

 Original Set =  {'kiwi', 'mango', 'apple', 'banana', 'orange'}

Set in Descending =  ['orange', 'mango', 'kiwi', 'banana', 'apple']

How to use reverse and key arguments in Python set sorted?

This example shows how to use key arguments on set items. Here, we declared a function to find the string length. Next, we use this Python sort function as the key value on set items. It means set elements sorted based on the length in ascending.

In the next line, we used the reverse argument also. It sorts the set elements in descending based on their length.

def stringlength(item):
    return len(item)

setCountryExample = {'USA', 'UK', 'Canada', 'India', 'Australia'}
print("\n Original = ", setCountryExample)

ascCountrySet = sorted(setCountryExample, key = stringlength)
print("\nString Set = ", ascCountrySet)

descCountrySet = sorted(setCountryExample, reverse = True, key = stringlength)
print("Desc = ", descCountrySet)

 Original =  {'UK', 'Australia', 'Canada', 'India', 'USA'}

String Set =  ['UK', 'USA', 'India', 'Canada', 'Australia']
Desc =  ['Australia', 'Canada', 'India', 'USA', 'UK']

This set example is the same as the above. We just replaced the user-defined with the built-in standard len function.

setCountryExample = {'USA', 'UK', 'Canada', 'India', 'Australia'}
print("\n Original = ", setCountryExample)

descCountrySet = sorted(setCountryExample, reverse = True, key = len)
print("Desc = ", descCountrySet)

 Original =  {'Australia', 'India', 'UK', 'Canada', 'USA'}

Desc =  ['Australia', 'Canada', 'India', 'USA', 'UK']

Python Sort String Examples

This section shows you how to sort strings in ascending and Descending.

You can’t use this directly on the string items. To achieve the same, first, we order them in ascending. It split a string into individual characters. Next, we used the join method to join the individual characters.

First, we declared a string. Next, we used this Python method and join method to sort them in ascending. Here, this method uses alphabetically to arrange the characters in a string. Next, we use the reverse= true argument to order the string in Descending.

stringExample = 'tutorialgateway'
print("\n Original String = ", stringExample)

newString = ''.join(sorted(stringExample))
print("\n String in Ascending = ", newString)

descString = ''.join(sorted(stringExample, reverse = True))
print("\n String in Descending = ", descString)

 Original String =  tutorialgateway

 String in Ascending =  aaaegilortttuwy

 String in Descending =  ywutttroligeaaa

Python Sort Dictionary Examples

The following Python examples show how to sort Dictionary items in ascending and descending.

We can use the same function on dictionary items to arrange them in ascending and descending. Here, we are using the keys, values, and items functions to extract keys, values, and items from the dictionary.

In this example, we declared a dictionary. Next, we used this Python method on dictionary keys to sort the dictionary keys in ascending. Second, we operated on dictionary values to arrange the dictionary values in ascending. Third, we used it on items to organize the complete dictionary items based on a dictionary key.

dictIntExample = {1: 10, 4: 70, 3: 30, 5: 50, 2: 200 }
print("\nOriginal Dictionary = ", dictIntExample)

ascKDictionary = sorted(dictIntExample.keys())
print("\nDictionary Keys in Ascending = ", ascKDictionary)

ascVDictionary = sorted(dictIntExample.values())
print("Dictionary Vals in Ascending = ", ascVDictionary)

ascDictionary = sorted(dictIntExample.items())
print("Dictionary in Ascending= ", ascDictionary)

Original Dictionary =  {1: 10, 4: 70, 3: 30, 5: 50, 2: 200}

Dictionary Keys in Ascending =  [1, 2, 3, 4, 5]
Dictionary Vals in Ascending =  [10, 30, 50, 70, 200]
Dictionary in Ascending=  [(1, 10), (2, 200), (3, 30), (4, 70), (5, 50)]

If we add the reverse argument in the above example, the dictionary keys, values, and items are in reverse or descending.

Python Sort the Dictionary by Keys and Values in reverse

In this Dictionary example, we used the reverse argument and assigned the value as True. The following code performs on the dictionary keys, values, and items in descending.

dictStrExm = {3: 'cherry', 10: 'banana' , 5: 'orange', 9: 'kiwi'}
print("\nOriginal = ",dictStrExm)

descKDictionary = sorted(dictStrExm.keys(), reverse = True)
print("\nKeys in Desc = ", descKDictionary)

descVDictionary = sorted(dictStrExm.values(), reverse = True)
print("Values in Desc = ", descVDictionary)

descDictionary = sorted(dictStrExm.items(), reverse = True)
print("Dictionary in Desc= ", descDictionary)

Original =  {3: 'cherry', 10: 'banana', 5: 'orange', 9: 'kiwi'}

Keys in Desc =  [10, 9, 5, 3]
Values in Desc =  ['orange', 'kiwi', 'cherry', 'banana']
Dictionary in Desc=  [(10, 'banana'), (9, 'kiwi'), (5, 'orange'), (3, 'cherry')]