Sorting a list is pretty easy: Python has built-in support for sorting lists.

Start with some data: Create a list of numbers and then call the sort() method. This method is directly called on the list object. This will work with any list, including list of pairs.

Related course: Complete Python Programming Course & Exercises

Sort example

Sort list

We define a list (x) with a bunch of numbers. Then call the sort method on the list object. We do not need to save the return variable, simply calling the method is enough.

1
2
3
x = [3,6,21,1,5,98,4,23,1,6]
x.sort()
print(x)

Save the program (sort1.py) and run it. This will output all numbers in low to high order.

Do you have a list of strings? Strings can also be sorted.

1
2
3
words = ["Be","Car","Always","Door","Eat" ]
words.sort()
print(words)

By simply calling the .sort() method, you can sort a list with a number of items.

You do not need to use a return variable when doing this, because lists are objects (more on this later in the OOP section). For now just remember that you can call .sort() on lists.

Reverse order

To sort in reverse order, combine it with the method reverse()

1
2
3
4
x = [3,6,21,1,5,98,4,23,1,6]
x.sort()
x = list(reversed(x))
print(x)

All of the numbers will be shown in reverse order.

So what’s happening here?

First the list is sorted with x.sort().

Then it’s given to the function reversed() which takes a list as parameter. But, the function does not return a list object but an iterator. The method list() converts the output of reversed() and converts it to a list object.

sort list

Best way to sort in reverse order

You can sort the list in a more elegant way:

1
words = words[::-1]

What’s this trickery?

The technique of slicing is used on the list. It means slice the list, starting at the first character, ending at the last character and with step size of -1 (reverse).

If you are a beginner, then I highly recommend this book.

Exercise

  1. Given a list with pairs, sort on the first element

    1
    x = [ (3,6),(4,7),(5,9),(8,4),(3,1)]
  2. Now sort on the second element

Download examples