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 Bootcamp: Go from zero to hero in Python

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.

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.

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()

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:

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).

Exercise

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

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

Download answers