Python List Sort

Posted 

4 min read

Sorting data is one of the most common tasks when working with Python. For example, you may want to sort a list of team members by name, or a list of projects in order of priority.

This article describes how to sort lists in Python.

Python sort() and sorted()

In Python, you can sort a list using the built-in list.sort() method or the built-in sorted() function.

The sorted() function creates a new sorted list, while the list.sort() method sorts the list in place. If you want to keep, the unsorted list use the sorted() function. Another difference is that the sorted() function works on any iterable object.

The syntax of sort() and sorted() is as follows:

list.sort(key=function, reverse=Boolean)
sorted(iterable, key=function, reverse=Boolean)

The optional keyword arguments key and reverse have the following meaning:

  • key - Function that takes one argument and transforms it before the comparison. The function must return one value that is used for the sort comparison.
  • reverse - The value of reverse can be either True or False. The default value is True. When this argument is set to false, the list is sorted in reverse order.

Elements of the list are compared using the “less than” (<) operator and sorted in ascending order. The < operator doesn’t support comparing a string to an integer, so if you have a list containing strings and integers, the sort operation will fail.

The following example shows how to sort a list of strings in alphabetical order:

directions = ["north", "east", "south", "west"] 

directions.sort()

print('Sorted list:', directions)
Sorted list: ['east', 'north', 'south', 'west']

If you want to keep the original list unchanged use the sorted() function:

directions = ["north", "east", "south", "west"] 

sorted_directions = sorted(directions)

print('Sorted list:', sorted_directions)
Sorted list: ['east', 'north', 'south', 'west']

To sort the list in reverse (descending) order set the reverse argument to True:

directions = ["north", "east", "south", "west"] 

directions.sort(reverse=True)

print('Sorted list:', directions)
Sorted list: ['west', 'south', 'north', 'east']

Sorting with Function

The key argument accepts a function and allows you to perform more complex sorting operations.

The most simple example would be to sort the elements according to their length:

directions = ["Arya", "Daenerys", "Jon", "Brienne"] 

directions.sort(key=len)

print('Sorted list:', directions)

We’re using the len() function to return the number of characters in the string, which is used as a comparator:

Sorted list: ['Jon', 'Arya', 'Brienne', 'Daenerys']

You can also create a custom function and use it as a key argument for comparison. Here is an example showing how to sort a list of integers according to the sum of their digits:


def sum_digits(num): 
    digits = [int(x) for x in str(num)] 
    return sum(digits) 
      
numbers = [23, 77, 19, 310, 219] 

numbers.sort(reverse=True, key=sum_digits)

print('Sorted list:', numbers)
Sorted list: [77, 219, 19, 23, 310]

Another example would be to use the key argument to sort a complex list, such as list of tuples:

numbers = [(3, 14), (1, 61), (2, 71)]

numbers.sort(key=lambda k: k[0])

print('Sorted list:', numbers)

We’re using an anonymous (lambda) function that returns the first element of the tuple. The list is sorted by the value returned from the function:

Sorted list: [(1, 61), (2, 71), (3, 14)]

The same approach can be used to sort a list of dictionaries:

elements = [
    {'name': 'Germanium', 'number': 25, 'symbol': 'ge'},
    {'name': 'Silver', 'number': 47, 'symbol': 'ag'},
    {'name': 'Iron', 'number': 26, 'symbol': 'fe'},
]

elements.sort(key=lambda k: k['name'])

print('Sorted list:', elements)

The lambda function returns the value of the name key, which is used for comparison:

Sorted list: [
    {'name': 'Germanium', 'number': 25, 'symbol': 'ge'}, 
    {'name': 'Iron', 'number': 26, 'symbol': 'fe'}, 
    {'name': 'Silver', 'number': 47, 'symbol': 'ag'}
]

A better and faster way to sort a complex function is to use the Operator module functions. Here is an example:

from operator import itemgetter

elements = [
    {'name': 'Germanium', 'number': 25, 'symbol': 'ge'},
    {'name': 'Silver', 'number': 47, 'symbol': 'ag'},
    {'name': 'Iron', 'number': 26, 'symbol': 'fe'},
]

elements.sort(key=itemgetter('symbol')) 

print('Sorted list:', elements)

The itemgetter function fetches the value of the key symbol:

Sorted list: [
    {'name': 'Silver', 'number': 47, 'symbol': 'ag'},
    {'name': 'Iron', 'number': 26, 'symbol': 'fe'},
    {'name': 'Germanium', 'number': 25, 'symbol': 'ge'}
]

Conclusion

We have shown you how to sort lists in Python using the sort() method and sorted() function.

If you have any questions or feedback, feel free to leave a comment.