Python list - sort by ascending or descending

A Python list can be sorted by using sort().

a = [2, 3, 1]

a.sort()

print(a)  # [1, 2, 3]

The default order is ascending. If reverse option is true, the sorted order is descending.

a = [2, 3, 1]

a.sort(reverse=True)

print(a)  # [3, 2, 1]

sorted()

sort() updates the original list but sorted() returns the new sorted list.

s = [3, 1, 2]

s1 = sorted(s)
s2 = sorted(s, reverse=True)
s3 = sorted(s, reverse=False)

print(s1)
print(s2)
print(s3)

Python List

Python Tutorial