How to sort a list of numbers in ascending or descending order with python ?

Published: January 30, 2019

Updated: March 23, 2023

DMCA.com Protection Status

The most basic way to sort a list of numbers in Python is by using the .sort() method. This works for both ascending and descending orders. Examples:

Using sort()

Let's create a list:

import random

myList = [i for i in range(10)]

random.shuffle(myList)

print(myList)

Output

[4, 9, 8, 7, 0, 3, 5, 2, 6, 1]

Ascending order

For an ascending order, simply call the .sort() method on your list and it will arrange all values from lowest to highest

myList.sort()

print(myList)

Ouput

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Descending order

If you wish to sort the list in descending order, use the reverse flag - set it to True and the list will be arranged from highest to lowest. It can be done like this: my_list.sort(reverse=True).

myList.sort(reverse=True)

print(myList)

output

[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Using sorted()

Another option is to use the sorted() function which has similar syntax as sort(). The main difference between them is that sorted() will return a new sorted list while .sort() sorts the original one.

Ascending order

To use it, simply call the sorted() function and pass it your list as an argument.

newList = sorted(myList)

print( newList )

Ouput

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Note that with sorted() the original list myList is not modified

myList

Ouput

[4, 9, 8, 7, 0, 3, 5, 2, 6, 1]

Can be used in a loop, example:

>>> for i in sorted(l):
...     print(i)
... 
0
1
2
3
4
5
6
7
8
9

Descending order

To get the list in descending order just use reverse=True

sorted(l,reverse=True)

Ouput

[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

References

Links Site
sort() python doc
sorted() python doc