PythonMastery
Python programs · Lists · beginner

Sort a list in Python (ascending and descending)

Sort a list of numbers in ascending and descending order with sorted() and list.sort(), and sort words without capital letters coming first.

sorted() returns a new sorted list. list.sort() sorts the list itself. Both take reverse=True for descending order.

The program

python
numbers = [3, 1, 4, 1, 5, 9, 2, 6]

print("Ascending: ", sorted(numbers))
print("Descending:", sorted(numbers, reverse=True))
print("Original:  ", numbers)

numbers.sort()
print("After sort():", numbers)
output
Ascending:  [1, 1, 2, 3, 4, 5, 6, 9]
Descending: [9, 6, 5, 4, 3, 2, 1, 1]
Original:   [3, 1, 4, 1, 5, 9, 2, 6]
After sort(): [1, 1, 2, 3, 4, 5, 6, 9]

How it works

Sorting words

Strings sort by character code, and every capital letter comes before every lower case letter. Use key=str.lower to compare the words as if they were all lower case:

python
names = ["grace", "Linus", "ada", "Hedy"]

print(sorted(names))
print(sorted(names, key=str.lower))
print(sorted(names, key=len))
output
['Hedy', 'Linus', 'ada', 'grace']
['ada', 'grace', 'Hedy', 'Linus']
['ada', 'Hedy', 'grace', 'Linus']

key is a function that Python calls on each item, and the list is sorted by the results. With key=len, shorter words come first. Words of the same length stay in their original order, because Python's sort is stable.

Learn the idea: Lists & Sequences, Functions & Scoping