Tutorial Gateway

  • C
  • C#
  • Java
  • Python
  • SQL
  • MySQL
  • Js
  • BI Tools
    • Informatica
    • Talend
    • Tableau
    • Power BI
    • SSIS
    • SSRS
    • SSAS
    • MDX
    • R Tutorial
    • Alteryx
    • QlikView
  • More
    • C Programs
    • C++ Programs
    • Go Programs
    • Python Programs
    • Java Programs

Python sort

by suresh

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)
Python Sort Example 1

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)
Python Sort Example 2

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)
Python Sort Example 3

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)
Python Sort Example 5

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. Next, 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)
Python Sort Example 6

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)
Python Sort Example 7

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)
Python Sort Example 8

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)
Python Sort Example 9

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)
Python Sort Example 10

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)
Python Sort Example 11

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)
Python Sort Example 12

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)
Python Sort Example 13

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)
Python Sort Example 14

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)
Python Sort Example 15

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)
Python Sort Example 16

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)
Python Sort Example 17

Placed Under: Python, Python Examples

  • Download and Install Python
  • Python Arithmetic Operators
  • Python Assignment Operators
  • Python Bitwise Operators
  • Python Comparison Operators
  • Python Logical Operators
  • Python If Statement
  • Python If Else
  • Python Elif Statement
  • Python Nested If
  • Python For Loop
  • Python While Loop
  • Python Break
  • Python Continue
  • Python Dictionary
  • Python datetime
  • Python String
  • Python Set
  • Python Tuple
  • Python List
  • Python List Comprehensions
  • Python Lambda Function
  • Python Functions
  • Python Types of Functions
  • Python Iterator
  • Python File Handling
  • Python Directory
  • Python Class
  • Python classmethod
  • Python Inheritance
  • Python Method Overriding
  • Python Static Method
  • Connect Python and SQL Server
  • Python SQL Create DB
  • Python SQL Select Top
  • Python SQL Where Clause
  • Python SQL Order By
  • Python SQL Select Statement
  • Python len Function
  • Python max Function
  • Python map Function
  • Python print Function
  • Python sort Function
  • Python range Function
  • Python zip Function
  • Python Math Functions
  • Python String Functions
  • Python List Functions
  • Python NumPy Array
  • NumPy Aggregate Functions
  • NumPy Arithmetic Operations
  • Python Numpy Bitwise operators
  • Numpy Comparison Operators
  • Numpy Exponential Functions
  • Python Numpy logical operators
  • Python numpy String Functions
  • NumPy Trigonometric Functions
  • Python random Array
  • Python numpy concatenate
  • Python numpy Array shape
  • Python pandas DataFrame
  • Pandas DataFrame plot
  • Python Series
  • Python matplotlib Histogram
  • Python matplotlib Scatter Plot
  • Python matplotlib Pie Chart
  • Python matplotlib Bar Chart
  • Python List Length
  • Python sort List Function
  • Python String Concatenation
  • Python String Length
  • Python substring
  • Python Programming Examples

Copyright © 2021 · All Rights Reserved by Suresh

About Us | Contact Us | Privacy Policy