Python

How to Sort Lists in Python

This article will cover a guide on sorting lists in Python. A Python list object is a collection of one or more comma separated items. It is an “iterable” object and its elements can be accessed by iterating over the list using loop statements and other expressions. You can sort a Python list using “sort” and “sorted” methods, both of them are explained in the article. All code samples in this article are tested with Python 3.9.5 in Ubuntu 21.04.

Sort Method

The sort method sorts a list “in-place”. In other words, it will modify the list object you are going to sort and reorder its element. If you don’t require the original list and don’t mind the list changing its order of elements “in-place”, this is the most efficient method in Python to sort a list. Consider this example:

l = [2, 8, 6, 4]

l.sort()

print (l)

After running the above code sample, you should get the following output:

[2, 4, 6, 8]

The first statement in the code sample defines a list. Next, “sort” method is called upon the list. When you print the list, you can see that the original list’s order has been changed.

By default, Python sorts a list in ascending order. If you want to sort a list in descending order, use “reverse” method, as shown in the code sample below:

l = [2, 8, 6, 4]

l.sort()

l.reverse()

print (l)

After running the above code sample, you should get the following output:

[8, 6, 4, 2]

The “reverse” method also changes a Python list “in-place” without creating a new list.

If your list contains string elements, calling the “sort” method on it will order it alphabetically where symbols and numbers are ordered first. Take a look at the code sample below:

l = ["s", "a", "z", "4", "#"]

l.sort()
print (l)

After running the above code sample, you should get the following output:

['#', '4', 'a', 's', 'z']

You can also use the reverse method on a list containing string elements.

l = ["s", "a", "z", "4", "#"]

l.sort()

l.reverse()

print (l)

After running the above code sample, you should get the following output:

['z', 's', 'a', '4', '#']

Sorted Method

The sorted method also sorts a Python list, in the same way as the “sort” method. However, instead of modifying the original list, it returns a new list so that your original list is left untouched in case you want to reuse it. Consider the code below:

list1 = ["s", "a", "z", "4", "#"]

list2 = sorted(list1)

print (list1, list2)

After running the above code sample, you should get the following output:

['s', 'a', 'z', '4', '#'] ['#', '4', 'a', 's', 'z']

You can see in the output that “list1” is intact and “list2” now has sorted elements. You can also use the “reverse” method on “list2” to change its ordering methodology.

Reverse Argument

You can use the “reverse” argument as an alternative to reverse function in both “sort” and “sort” methods to get a sorted list in descending order. Just supply it a “True” value to change the order of sorting:

list1 = ["s", "a", "z", "4", "#"]

list2 = sorted(list1, reverse=True)

print (list1, list2)

After running the above code sample, you should get the following output:

['s', 'a', 'z', '4', '#'] ['z', 's', 'a', '4', '#']

Using Key Function to Specify Your Own Logic for Sorting Elements of a List

In both “sort” and “sorted” methods, you can specify an additional “key” argument that takes a callable function as its value. This key argument can be assigned an existing function from built-in Python modules or you can supply your own function with custom logic. Take a look at the code sample below:

list1 = ["abcde", "xyz", "ijkl"]

list2 = sorted(list1, key=len)

print (list1, list2)

list1.sort(key=len)

print (list1)

After running the above code sample, you should get the following output:

['abcde', 'xyz', 'ijkl'] ['xyz', 'ijkl', 'abcde']

['xyz', 'ijkl', 'abcde']

The code sample illustrates usage of “key” argument in both “sorted” and “sort” methods. The function supplied to it is called “len” which determines the length of a string object or an iterable. The function or callable should originally take only one argument. You assign it to the “key” argument without using braces. The callable function supplied to the “key” argument is called upon each element of the list. The values returned from this callable method are then used as a key for sorting the list. Hence, supplying the “len” function to the “key” argument sorts elements of a list in the order of their length, that is, from shortest to longest. As stated earlier, you can always use the “reverse” method to reverse the sorting methodology.

You can also use your own custom function or one-liner lambda functions that return the value of a single expression. Take a look at the code sample below where a list is having tuples of current inventory of fruit crates:

list1 = [("mango", 99), ("orange", 51), ("banana", 76)]

list1.sort(key=lambda inventory: inventory[1])

print (list1)

After running the above code sample, you should get the following output:

[('orange', 51), ('banana', 76), ('mango', 99)]

The “lambda” function is supplied with an argument “inventory”, which is each element of the list in tuple form. It then returns the second element of each tuple as key (at index 1). The sort function then sorts all tuples by its second element in ascending order. You can also use the “reverse” function or the “reverse” argument on the end result to reverse the order of sorting.

Conclusion

These are some ways using which you can sort the contents of an iterable list in Python. The “key” argument allows you to write your own custom sorting logic, suitable for applications that may have different needs than the built-in sort methods.

About the author

Nitesh Kumar

I am a freelancer software developer and content writer who loves Linux, open source software and the free software community.