How to sort numbers in Python?


Python List - Sort numbers

In this tutorial, you will learn how to sort a given list of numbers using sort() method of list instance(), with examples.

To sort a list of numbers nums in ascending order, call sort() method on the list. By default, the sort() method sorts the numbers in place in ascending order.

nums.sort()

To sort a list of numbers nums in descending order, call sort() method on the list and specify named argument reverse=True. The sort() method with the specified argument sorts the numbers in place in descending order.

nums.sort(reverse=True)

1. Sort numbers in ascending order in Python

Let us take a list of numbers in nums, and sort them in ascending order using sort() method.

Python Program

nums = [30, 50, 40, 10, 20, 70, 60]
print(f"Given numbers  : {nums}")

nums.sort()
print(f"Sorted numbers : {nums}")

Output

Given numbers  : [30, 50, 40, 10, 20, 70, 60]
Sorted numbers : [10, 20, 30, 40, 50, 60, 70]

The numbers are sorted in ascending order.

2. Sort numbers in descending order in Python

Let us take a list of numbers in nums, and sort them in descending order using sort() method. Pass reverse=True to the sort() method.

Python Program

nums = [30, 50, 40, 10, 20, 70, 60]
print(f"Given numbers  : {nums}")

nums.sort(reverse=True)
print(f"Sorted numbers : {nums}")

Output

Given numbers  : [30, 50, 40, 10, 20, 70, 60]
Sorted numbers : [70, 60, 50, 40, 30, 20, 10]

The numbers are sorted in descending order.

Summary

In this tutorial of Python Lists, we have seen how to sort numbers in a list in ascending or descending order, using sort() method, with examples.