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

Using sorted()

sorted() is a built-in function in Python.

  • The original order of values is unchanged once it’s called.

  • It returns an ordered list.

    numbers = [1, 5, 3, 2, 4]
    sorted_numbers = sorted(numbers)
    print(sorted_numbers)
    print(numbers)

    Output:

    [1, 2, 3, 4, 5]

    [1, 5, 3, 2, 4]

Using sort()

The sort() is a method of list class. It orders in place and return nothing.

sorted_numbers = numbers.sort()
print(sorted_numbers)
print(numbers)

# Output:
# None
# [1, 2, 3, 4, 5]

Sort in reverse order

numbers = [1, 5, 3, 2, 4]
sorted_numbers = sorted(numbers, reverse=True)
print(sorted_numbers)
print(numbers)

# Output:
# [5, 4, 3, 2, 1]
# [1, 5, 3, 2, 4]


numbers.sort(reverse=True)
print(numbers)

# Output:
# [5, 4, 3, 2, 1]

Sort dictionary

Note that the keys in a dictionary must be unique. In the following example, even if two 5s are initialized in the number list, they will be deduplicated.

numbers_set = {20, 5, 3, 2, 4, 5}
sorted_numbers_set = sorted(numbers_set)
print(numbers_set)
print(sorted_numbers_set)
print(set(sorted_numbers_set))

# Output:
# {2, 3, 4, 5, 20}
# [2, 3, 4, 5, 20]
# {2, 3, 4, 5, 20}

Sort tuple

Example 1:

numbers_tuple = (10, 5, 3, 2, 4, 5)
sorted_numbers_tuple = sorted(numbers_tuple)
print(numbers_tuple)
print(sorted_numbers_tuple)
print(tuple(sorted_numbers_tuple))

# Output:
# (10, 5, 3, 2, 4, 5)
# [2, 3, 4, 5, 5, 10]
# (2, 3, 4, 5, 5, 10)

Example 2:

fruits = [("apple", 10), ("orange", 6), ("banana", 9), ("pear", 3)]
sorted_fruits = sorted(fruits, key=lambda x: x[1], reverse=True)
print(sorted_fruits)

# Output:
# [('apple', 10), ('banana', 9), ('orange', 6), ('pear', 3)]

Example 3:

from collections import namedtuple

Student = namedtuple("Student", "name, age, grade")
students = [
    Student("bill", 11, 97),
    Student("Andy", 12, 95),
    Student("Harry", 10, 100),
    Student("Thor", 11, 96),
]
sorted_students = sorted(students, key=lambda x: getattr(x, "grade"), reverse=True)
print(sorted_students)
print(students)

# Output:
# [Student(name='Harry', age=10, grade=100), Student(name='bill', age=11, grade=97), Student(name='Thor', age=11, grade=96), Student(name='Andy', age=12, grade=95)]
# [Student(name='bill', age=11, grade=97), Student(name='Andy', age=12, grade=95), Student(name='Harry', age=10, grade=100), Student(name='Thor', age=11, grade=96)]