Python sort

How to use the Python sort function, and sorted function with practical examples. Python sort Objects like Lists, Dictionary, Tuples, Sets, and Strings is one of the most commonly asked questions.

In Python programming, we have functions to sort the objects, and they are sort and sorted. The sort function works only in list items, and use sorted for the remaining objects. The syntax of this sort and sorted functions in Python are

# Python Sort Syntax

# Sort List Items in Ascending Order
list_Name.sort()

# Sort List Items in Reverse Order or Descending Order
list_Name.sort(reverse = True)

# Sort List Items using Functions
list_Name.sort(key = Function_Name)

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


# Sorted function Syntax
# Sort Items in Ascending Order
sorted(Object_Name)

# Sort Items in Reverse Order or Descending Order
sorted(Object_Name, reverse = True)

# Sort Items using Functions
sorted(Object_Name, key = Function_Name)

# Sort Items in Reverse Order using Functions
sorted(Object_Name, reverse = True, key = Function_Name)

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

Python sort List Items Examples

Sorting the List items in ascending & descending order using the list sort function.

Sort List Items Example 1

The python sort function works on list items to sort them in ascending order. In this example, first, we declared an integer list. Next, we used sort function to sort that integer list and string list in ascending order. Here, sort function uses alphabetical order to sort string-list.

TIP: Please refer sort article to know about this sort function on List items.

# Python Sort List Example

listexample = [13, 98, 45, 125, 6, 22, 9, 78]
print("\n Original List = ", listexample)

listexample.sort()
print("The Sorted List = ", listexample)

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

liststring.sort()
print("The Sorted String List = ", liststring)

Sort List Items Output


 Original List =  [13, 98, 45, 125, 6, 22, 9, 78]
The Sorted List =  [6, 9, 13, 22, 45, 78, 98, 125]

 Original List String =  ['orange', 'banana', 'kiwi', 'grape', 'blackberry']
The Sorted String List =  ['banana', 'blackberry', 'grape', 'kiwi', 'orange']

Python Sort List Reverse Example 2

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

# Python Sort List Example

listexample = [13, 98, 125, 22, 9, 78]
print("\n Original List = ", listexample)

listexample.sort(reverse = True)
print("The Sorted List = ", listexample)

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

liststring.sort(reverse = True)
print("The Sorted String List = ", liststring)

Sort List Items in reverse order Output


 Original List =  [13, 98, 125, 22, 9, 78]
The Sorted List =  [125, 98, 78, 22, 13, 9]

 Original List String =  ['orange', 'blackberry', 'kiwi', 'grape', 'banana']
The Sorted String List =  ['orange', 'kiwi', 'grape', 'blackberry', 'banana']

Python sort List Example 3

The List sort function has another argument called a key. This key accepts any function, and that function determines the sorting factor.

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

In the next couple of lines, we used the reverse argument, along with this key argument. It means list items sorted in the descending order based on the second value in the nested list.

 # Python Sort Example

def secondValue(value):
    return value[1]

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

# Sort List in Ascending Order using First item
listexample.sort()
print("\nAscending Order using First = ", listexample)

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

# Sort Python List in Descending Order
# Sort List in Descending Order using First item
listexample.sort(reverse = True)
print("\nDescending Sorted List = ", listexample)

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

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

Ascending Order using First =  [[14, 151], [17, 222], [99, 77], [222, 13]]
Ascending Order using Second =  [[222, 13], [99, 77], [14, 151], [17, 222]]

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

Sort Tuple in Python Examples

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

Sort Tuple Example 1

The python sort function sorts the given tuple in ascending order. The below code sorts the elements in an integer tuple. In this example, first, we declared a string tuple. Next, we used python sort function to sort them in ascending order. Here, sort function uses alphabetical order to sort string tuple.

 # Python Sort Tuple Example

tupleIntexample = (9, -5, 7, 0, 24, -1, 2, 10)
print("\n Original Integer Tuple = ", tupleIntexample)

ascSorted = sorted(tupleIntexample)
print("The Sorted Integer Tuple = ", ascSorted)

# Python sort Tuple in Descending Order
descSorted = sorted(tupleIntexample, reverse = True)
print("Sorted Integer Tuple in Descending = ", descSorted)
Python Sort Example 4

Python Sort Tuple Reverse Example 2

The Python sorted function uses its argument called reverse = True. It sorts the tuple items in reverse order or descending order. The below code sort the integer and string tuple elements in Descending order or reverse order.

 # Python Sort Tuple Example

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

ascSorted = sorted(tupleexample)
print("The Sorted Tuple = ", ascSorted)

# Python sort Tuple in Descending Order
descSorted = sorted(tupleexample, reverse = True)
print("Descending Sorted Tuple = ", descSorted)

sort tuple items in reverse order output


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

Python sort Tuple Example 3

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

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

 # Python Sort Tuple Example

def length(item):
    return len(item)

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

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

# Python sort Tuple in Descending Order
descSorted = sorted(tupleexample, reverse = True, key = length)
print("Desc Sorted Tuple by Length = ", descSorted)

sorted function on tuple items output


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

Python sort Tuple Example 4

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

# Python Sort Tuple Example

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

ascSorted = sorted(tupleexm1, key = len)
print("Sorted Tuple by Length = ", ascSorted)

# Python sort Tuple in Descending Order
descSorted = sorted(tupleexm1, reverse = True, key = len)
print("Desc Sorted Tuple by Length = ", descSorted)

Tuple sorted output


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

Python Set Sorted Examples

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

Python Set Sorted Example 1

The python sorted function is the one that you can use to sort the set items in ascending order and descending order.

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

 # Python Sort Set Example

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

print("\nThe Sorted Set = ", sorted(setExample))

# Python sort Set in Descending Order
descSet = sorted(setExample, reverse = True)
print("Sorted Set in Descending = ", descSet)

set sorted output


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

The Sorted Set =  [-15, -4, 0, 7, 10, 12, 17, 22]
Sorted Set in Descending =  [22, 17, 12, 10, 7, 0, -4, -15]

Python Set Sorted Reverse Example 2

In this set reverse sorted example, we are using the sorted function on the set of string values — the below code sort the string set in ascending and descending order.

 # Python Sort Set Example

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

print("\nSorted String Set = ", sorted(setStringExample))

# Python sort Set in Descending Order
descStrSet = sorted(setStringExample, reverse = True)
print("Sorted Set in Desc = ", descStrSet)

set sorted reverse argument output


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

Sorted String Set =  ['apple', 'banana', 'kiwi', 'mango', 'orange']
Sorted Set in Desc =  ['orange', 'mango', 'kiwi', 'banana', 'apple']

Python Set Sorted Example 3

This Python sort example shows how to use key arguments on set items. Here, we declared a function to find the string length. Next, we are using this function as the key-value on set items. It means, set elements sorted based on the length in the ascending order. In the next line, we used the reverse argument also. It sorts the set elements in descending order based on their length.

 # Python Sort Set Example
 
def stringlength(item):
    return len(item)

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

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

# Python sort Set in Descending Order
descCountrySet = sorted(setCountryExample, reverse = True, key = stringlength)
print("Sorted Set in Desc = ", descCountrySet)

sorted function on set items output


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

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

Python sort Set reverse Example 4

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

 # Python Sort Set Example

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

ascCountrySet = sorted(setCountryExample, key = len)
print("\nSorted String Set = ", ascCountrySet)

# Python sort Set in Descending Order
descCountrySet = sorted(setCountryExample, reverse = True, key = len)
print("Sorted Set in Desc = ", descCountrySet)

sort set items in reverse order output


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

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

Python Sort String Examples

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

Sort String Example 1

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

First, we declared a string. Next, we used the sorted and join functions to sort them in ascending order. Here, the sorted function uses the alphabetical order to sort the characters in a string. Next, we are using the reverse= true argument to sort the string in Descending order.

 # Python Sort String Example

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

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

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

sort function on string data


 Original String =  tutorialgateway

 Sorted String in Ascending =  aaaegilortttuwy

 Sorted String in Descending =  ywutttroligeaaa

Python Sort String reverse Example 2

The Python sort string reverse example is the same as the above example. However, this time, we are allowing the user to enter their own string. Next, we are sorting the user entered string in both the ascending and Desc order or reverse order.

# Python Sort String Example

strExample = input("Please Enter Your Own String : ")
print("\n Original String = ", strExample)

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

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

string sort reverse Function output

Please Enter Your Own String : pythontutorial

 Original String =  pythontutorial

 Sorted String in Ascending =  ahilnooprtttuy

 Sorted String in Descending =  yutttrpoonliha

Python Dictionary Sorted Examples

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

Python Dictionary Sorted Example 1

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

In this Python sorted example, we declared a dictionary. Next, we used a sorted function on dictionary keys to sort the dictionary keys in ascending order. Second, we used a sorted function on dictionary values to sort the dictionary values in ascending order. Third, we used sorted function on items to sort the complete dictionary items based on a dictionary key.

 # Python Sort Dictionary Example

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

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

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

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

sorted function on dictionary items output


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

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

Dictionary Sorted reverse Example 2

The dictionary reverse sorted example is the same as the above example. However, we used the reverse = true. It means the Python sorted function sorts the dictionary keys, values, items in reverse order, or descending order.

 # Python Sort Dictionary Example

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

descKDictionary = sorted(dictExample.keys(), reverse = True)
print("\nSorted Dictionary Keys in Descending = ", descKDictionary)

descVDictionary = sorted(dictExample.values(), reverse = True)
print("Sorted Dictionary Values in Descending = ", descVDictionary)

descDictionary = sorted(dictExample.items(), reverse = True)
print("Sorted Dictionary in Descending= ", descDictionary)

dictionary reverse sorted output


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

Sorted Dictionary Keys in Descending =  [5, 4, 3, 2, 1]
Sorted Dictionary Values in Descending =  [200, 70, 50, 30, 10]
Sorted Dictionary in Descending=  [(5, 50), (4, 70), (3, 30), (2, 200), (1, 10)]

Dictionary Sorted Example 3

In this dictionary sort function example, we are using this sorted function on string dictionary values.

 # Python Sort Dictionary Example

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

ascKDictionary = sorted(dictStrExm.keys())
print("\nSorted Dictionary Keys in Ascending = ", ascKDictionary)

ascVDictionary = sorted(dictStrExm.values())
print("Sorted Dictionary Values in Ascending = ", ascVDictionary)

ascDictionary = sorted(dictStrExm.items())
print("Dictionary in Asc = ", ascDictionary)

dictionary sorted function output


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

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

Dictionary Sorted reverse Example 4

This Dictionary sorted example used the reverse argument and assigned True. The following code sorts the dictionary in descending order.

 # Python Sort Dictionary Example

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

descKDictionary = sorted(dictStrExm.keys(), reverse = True)
print("\nSorted Dictionary Keys in Descending = ", descKDictionary)

descVDictionary = sorted(dictStrExm.values(), reverse = True)
print("Sorted Dictionary Values in Descending = ", descVDictionary)

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

Dictionary sorted function with reverse argument output


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

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