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

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)

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)

sort list

Exercise

1. Given a list with pairs, sort on the first element
x = [ (3,6),(4,7),(5,9),(8,4),(3,1)]
  1. Now sort on the second element

Download answers