Python sort() and sorted() with Examples

How to Use sort() and sorted() in Python

In this tutorial, you'll learn how to use the sort() list method and sorted() function in Python.

Python lists have a built-in sort() method that can be used to sort a list in ascending, descending, or user-defined order. 

Unlike sort(), sorted() is a built-in function that builds a new sorted list from an iterable.

The sorted() function takes an iterable and returns a new sorted list.

Python sort() List Method

Syntax

The syntax of the Python sort() list method is as follows:

list.sort(reverse=False, key=function_name)

Parameters

  • reverse: The argument is optional and defaults to False, and if it is True, the sorted list will be in descending order
  • key: Optional and the function that serves as a key for comparison

Python sort() Examples

Sorting a List of Strings in Ascending Order

The following code sorts a list of strings, in ascending order:

list = ["Carrots", "Garlic", "Onion", "Lettuce", "Cabbage", "Okra", "Spinach", "Cucumber"]
list.sort();
print (list)

Output:

['Cabbage', 'Carrots', 'Cucumber', 'Garlic', 'Lettuce', 'Okra', 'Onion', 'Spinach']

Sorting a List of Strings in Descending Order

The following code sorts a list of strings, in descending order:

list = ["Carrots", "Garlic", "Onion", "Lettuce", "Cabbage", "Okra", "Spinach", "Cucumber"]
list.sort(reverse = True);
print (list)

Output:

['Spinach', 'Onion', 'Okra', 'Lettuce', 'Garlic', 'Cucumber', 'Carrots', 'Cabbage']

Sorting a List of Strings by the Last Character

The following code sorts a list of strings, by the last character of elements, in ascending order:

def get_last_character(list_item):
return list_item[len(list_item)-1]
list = ["Carrots", "Garlic", "Onion", "Lettuce", "Cabbage", "Okra", "Spinach", "Cucumber"]
list.sort(key=get_last_character);
print (list)

Output:

['Okra', 'Garlic', 'Lettuce', 'Cabbage', 'Spinach', 'Onion', 'Cucumber', 'Carrots']

Sorting a List of Tuples by Default

The following code is an example of sorting a list of tuples by default:

student_1 = ("10001", "John", "18") #("ID", "Name", "Age")
student_2 = ("10002", "James", "20")
student_3 = ("10003", "Roland", "15")
student_4 = ("10004", "Josh", "21")
students = [student_4, student_2, student_1, student_3]
print ("Before sorting:")
print (students)
print ("After sorting:")
students.sort()
print (students)

Output:

Before sorting:
[('10004', 'Josh', '21'), ('10002', 'James', '20'), ('10001', 'John', '18'), ('10003', 'Roland', '15')]
After sorting:
[('10001', 'John', '18'), ('10002', 'James', '20'), ('10003', 'Roland', '15'), ('10004', 'Josh', '21')]

Note that the sort() method sorts the first element of a tuple by default.

Sorting a List of Tuples using a User-Defined Function

The following is an example of sorting a list of tuples using a user-defined function:

def get_student_age(student):
return student[2]
def get_student_name(student):
return student[1]
student_1 = ("10001", "John", "22") #("ID", "Name", "Age")
student_2 = ("10002", "James", "20")
student_3 = ("10003", "Roland", "15")
student_4 = ("10004", "Josh", "21")
students = [student_4, student_2, student_1, student_3]
print ("Before sorting:")
print (students)
#sort by age descending
students.sort(key=get_student_age, reverse = True)
print ("Sort by age descending")
print (students)
#sort by name descending
students.sort(key=get_student_name, reverse = True)
print ("Sort by name descending")
print (students)

Output:

Before sorting:
[('10004', 'Josh', '21'), ('10002', 'James', '20'), ('10001', 'John', '22'), ('10003', 'Roland', '15')]
Sort by age descending
[('10001', 'John', '22'), ('10004', 'Josh', '21'), ('10002', 'James', '20'), ('10003', 'Roland', '15')]
Sort by name descending
[('10003', 'Roland', '15'), ('10004', 'Josh', '21'), ('10001', 'John', '22'), ('10002', 'James', '20')]

Python sorted() Function

The sorted() function takes an iterable and returns a sorted list.

Python sorted() Function Syntax

The syntax of the sorted() function is as follows:

sorted(iterable, reverse = False, key=function_name)

The sorted() Function Parameters

  • iterable: Required. It can be a list, set, tuple, or dictionary.
  • reverse: Optional and the default value is False, and if it is True a new created sorted list will be in descending order 
  • key: Optional and the function that serves as a key for comparison

Python sorted() Examples

Sorting a List of Numbers in Ascending Order

The following code sorts a list of number and returns a sorted list:

numbers = [1000, 200, 800, 500, 600, 700, 100, 300, 400, 100, 900]
sorted_numbers = sorted(numbers)
print (sorted_numbers)

Output:

[100, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000]

Sorting a Tuple of Numbers in Descending Order

The following code sorts a tuple of numbers and returns a sorted list:

numbers = (1000, 200, 800, 500, 600, 700, 100, 300, 400, 100, 900)
sorted_numbers = sorted(numbers, reverse = True)
print (sorted_numbers)

Output:

[1000, 900, 800, 700, 600, 500, 400, 300, 200, 100, 100]

Sorting a List of Dictionaries using a User-Defined Function

The following code illustrates an example of how to sort a list of dictionaries using a user-defined function:

def get_id(dict):
return dict["ID"]
def get_age(dict):
return dict["Age"]
def get_name(dict):
return dict["Name"]
students = [
{
"ID": "1004",
"Name": "James",
"Age": 19
},
{
"ID": "1001",
"Name": "John",
"Age": 18
},
{
"ID": "1003",
"Name": "Josh",
"Age": 17
}
]
#Sorted by ID ascending
sorted_students_id = sorted(students, reverse = False, key=get_id)
print ("Sorted by ID ascending:\n", sorted_students_id)
#Sorted by name ascending
sorted_students_name = sorted(students, reverse = False, key=get_name)
print ("Sorted by name ascending:\n", sorted_students_name)
#Sorted by age descending
sorted_students_age = sorted(students, reverse = True, key=get_age)
print ("Sorted by age descending:\n", sorted_students_age)

Output:

Sorted by ID ascending:
[{'ID': '1001', 'Name': 'John', 'Age': 18}, {'ID': '1003', 'Name': 'Josh', 'Age': 17}, {'ID': '1004', 'Name': 'James', 'Age': 19}]
Sorted by name ascending:
[{'ID': '1004', 'Name': 'James', 'Age': 19}, {'ID': '1001', 'Name': 'John', 'Age': 18}, {'ID': '1003', 'Name': 'Josh', 'Age': 17}]
Sorted by age descending:
[{'ID': '1004', 'Name': 'James', 'Age': 19}, {'ID': '1001', 'Name': 'John', 'Age': 18}, {'ID': '1003', 'Name': 'Josh', 'Age': 17}]

Read more:

In this tutorial, you've learned how to use the Python sort() list method and sorted() function.


See also:
Python return Statement with Examples
Python List Methods and Functions with Examples
Python abs() – Absolute Value in Python
Python Factorial – Find the Factorial of a Number
Python min() – Find the Smallest Value in Python

Leave a Comment