Sorting a list in Python lets you arrange its items in ascending or descending order.

Instead of writing long blocks of code to do that, Python has a built-in method that lets you sort the items in any list or array. We'll explain how to do that in this post.

How to Sort a List in Python

You can sort the items in a list or array using the Python sort() method.

The sort() method in Python accepts two optional arguments and the syntax looks like this:

        list.sort(key = function, reverse = True/False)

By default, the sort() method arranges the items of a list in ascending order:

        myList =  ["C", "D", "B", "A", "F"]

myList.sort()

print(myList)

Output: ['A', 'B', 'C', 'D', 'F']

You can use the reverse argument to view the list in descending order:

        myList =  ["C", "D", "B", "A", "F"]

myList.sort(reverse = True)

print(myList)

Output: ['F', 'D', 'C', 'B', 'A']

You can also arrange the items in a list by the length of each string.

To do so, create a function and pass it into the sort() method using the optional key argument:

        myList =  ["MUO", "Python", "JavaScript", "Sort", "Sortlists"]
def sortLength(item):
return len(item)

myList.sort(reverse = True, key = sortLength)

print(myList)

Output: ['JavaScript', 'Sortlists', 'Python', 'Sort', 'MUO']

How to Sort a List of Dictionaries in Python

You can use the sort() method to sort a list of dictionaries as well.

Let's sort the tasks in the dictionary below by their time:

        myArray =  [

{"Task": "Wash", "Time": 12.00},
{"Task":"Football", "Time": 24.00},
{"Task":"Sort", "Time": 17.00},
{"Task":"Code", "Time": 15.00}

]

def sortByTime(item):
return item["Time"]

myArray.sort(key = sortByTime)

print(myArray)

Since the values of time are integers, the above block of code rearranges the array based on the task time.

Related: How Arrays and Lists Work in Python

In addition to sorting the array above by time, you can also arrange it alphabetically using the tasks, which are strings.

To sort by string in the example array, you only need to change Time in the square bracket to Task:

        myArray =  [

{"Task": "Wash", "Time": 12.00},
{"Task":"Football", "Time": 24.00},
{"Task":"Sort", "Time": 17.00},
{"Task":"Code", "Time": 15.00}

]

def sortByTime(item):
return item["Task"]

myArray.sort(key = sortByTime)

print(myArray)

You can also sort the tasks in reverse order by setting reverse to true:

        myArray.sort(key = sortByTime, reverse = True)

You can also use a lambda function with sort() for cleaner code:

        myArray.sort(key = lambda getTime: getTime["Time"])

print(myArray)

How to Sort a Nested Python List

You can sort a nested list of tuples by the index of each nested element in that list.

For example, the code below uses the third item in each tuple to sort the list in ascending order:

        Alist = [(3, 19, 20), (2, 6, 0), (1, 8, 15), (7, 9, 3), (10, 19, 4)]

def sortByThirdIndex(a):
return a[2]

Alist.sort(key = sortByThirdIndex)
print(Alist)

Output: [(2, 6, 0), (7, 9, 3), (10, 19, 4), (1, 8, 15), (3, 19, 20)]

In the output above, the third item in each tuple increases from zero to twenty consecutively.

Note that this doesn't work with a Python set since you can't index it. On top of that, each nest in the list must belong to the same data type.

Related: What Is a Set in Python and How to Create One

However, to arrange the output in descending order:

        Alist.sort(key = getIndex, reverse = True)
print(Alist)

Output: [(3, 19, 20), (1, 8, 15), (10, 19, 4), (7, 9, 3), (2, 6, 0)]

Let's see how this looks with a lambda function as well:

        Alist = [(3, 19, 20), (2, 6, 0), (1, 8, 15), (7, 9, 3), (10, 19, 4)]

newList = sorted(Alist, key = lambda a: a[2])

print(newList)

Output: [(2, 6, 0), (7, 9, 3), (10, 19, 4), (1, 8, 15), (3, 19, 20)]

How to Sort a List Using the Sorted() Method

Alternatively, you can use the sorted() method.

Although it works similarly to the sort() method, it creates a new sorted list without modifying the original. Its syntax layout is also slightly different.

The syntax for the sorted() method generally looks like this:

        sorted(list, key = function, reverse = True/False)

So to sort a list using the sorted() method, you need to create a new variable for the sorted list:

        Alist = [(3, 19, 20), (2, 6, 0), (1, 8, 15), (7, 9, 3), (10, 19, 4)]

def getIndex(a):
  return a[2]

newList = sorted(Alist, key = getIndex)

print(newList)

Output: [(2, 6, 0), (7, 9, 3), (10, 19, 4), (1, 8, 15), (3, 19, 20)]

The sorted() method also accepts a lambda function as its key:

        Alist = [(3, 19, 20), (2, 6, 0), (1, 8, 15), (7, 9, 3), (10, 19, 4)]

newList = sorted(Alist, key = lambda a: a[2])

print(newList)

Output: [(2, 6, 0), (7, 9, 3), (10, 19, 4), (1, 8, 15), (3, 19, 20)]

Where Can You Apply List Sorting?

A solid grasp of the Python sort method is necessary for efficient programming. It lets you control how a list or array comes through, and you can always apply it in real-life projects. For instance, sorting a Python list can come in handy when rearranging data from an API or a database, so it makes more sense to an end-user.