Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to sort a list in Python

Introduction

Sorting is a common operation in programming, which involves arranging elements in a specific order. In this blog, we will explore how to sort a list in Python. If you are new to programming or Python, don't worry! We will try to explain the concepts in simple terms and avoid jargons as much as possible. We will also provide intuitions, analogies, and code examples to help you understand better.

A list in Python is a collection of elements that can be of different data types, such as integers, strings, or other objects. The elements in a list are ordered and can be accessed by their index. For example, a list of numbers [3, 1, 4, 1, 5, 9, 2] has seven elements, and we can access the first element (3) with the index 0.

Sorting a list

Sorting a list means arranging its elements in a specific order, such as ascending (from the smallest to the largest) or descending (from the largest to the smallest). There are various algorithms to sort a list, but Python provides built-in functions to do this easily. Let's start with the simplest one: the sorted() function.

The sorted() function

The sorted() function is a built-in Python function that returns a new sorted list from the specified iterable (e.g., a list, a tuple, or a string). By default, it sorts the list in ascending order. Here's how to use it:

numbers = [3, 1, 4, 1, 5, 9, 2]

sorted_numbers = sorted(numbers)

print(sorted_numbers)

Output:

[1, 1, 2, 3, 4, 5, 9]

Note that the sorted() function does not modify the original list. Instead, it creates a new sorted list. If you want to sort the list in descending order, you can pass the optional argument reverse=True to the function:

numbers = [3, 1, 4, 1, 5, 9, 2]

sorted_numbers = sorted(numbers, reverse=True)

print(sorted_numbers)

Output:

[9, 5, 4, 3, 2, 1, 1]

The sort() method

In addition to the sorted() function, Python lists also have a built-in method called sort(), which sorts the elements of the list in-place, meaning that it modifies the original list. The usage of the sort() method is similar to the sorted() function:

numbers = [3, 1, 4, 1, 5, 9, 2]

numbers.sort()

print(numbers)

Output:

[1, 1, 2, 3, 4, 5, 9]

To sort the list in descending order, you can pass the optional argument reverse=True to the method:

numbers = [3, 1, 4, 1, 5, 9, 2]

numbers.sort(reverse=True)

print(numbers)

Output:

[9, 5, 4, 3, 2, 1, 1]

Keep in mind that the sort() method only works with lists, whereas the sorted() function works with any iterable.

Sorting with a custom key

Sometimes, we need to sort a list based on a specific property or condition. For example, suppose we have a list of strings, and we want to sort them by their length. In this case, we can use the optional argument key to provide a custom sorting function. The key function should take one argument and return a value that will be used as the sorting key.

Let's see an example. We have a list of strings, and we want to sort them by length:

words = ['apple', 'banana', 'cherry', 'date', 'fig', 'grape']

# Define a custom sorting function that returns the length of a string
def word_length(word):
    return len(word)

sorted_words = sorted(words, key=word_length)

print(sorted_words)

Output:

['fig', 'date', 'apple', 'grape', 'banana', 'cherry']

In this example, our custom sorting function word_length() simply returns the length of the given word. The sorted() function then uses these lengths as sorting keys to sort the list.

Python has built-in functions that can simplify our custom sorting function. For example, we can use the len() function directly as the key:

words = ['apple', 'banana', 'cherry', 'date', 'fig', 'grape']

sorted_words = sorted(words, key=len)

print(sorted_words)

Output:

['fig', 'date', 'apple', 'grape', 'banana', 'cherry']

This code is equivalent to the previous example, but it's more concise and easier to read.

The key argument is also available for the sort() method:

words = ['apple', 'banana', 'cherry', 'date', 'fig', 'grape']

words.sort(key=len)

print(words)

Output:

['fig', 'date', 'apple', 'grape', 'banana', 'cherry']

Sorting with a custom comparison function

In some cases, we need even more control over the sorting process, such as when we need to compare elements using a custom comparison function. In Python, we can use the functools.cmp_to_key() function to convert a comparison function to a sorting key function.

A comparison function takes two arguments, a and b, and returns a negative, zero, or positive number, depending on whether a is considered smaller than, equal to, or greater than b. Let's see an example. We have a list of mixed-case strings, and we want to sort them case-insensitively:

from functools import cmp_to_key

words = ['Apple', 'banana', 'Cherry', 'Date', 'Fig', 'Grape']

# Define a custom comparison function that compares strings case-insensitively
def case_insensitive_compare(a, b):
    return (a.lower() > b.lower()) - (a.lower() < b.lower())

sorted_words = sorted(words, key=cmp_to_key(case_insensitive_compare))

print(sorted_words)

Output:

['Apple', 'banana', 'Cherry', 'Date', 'Fig', 'Grape']

In this example, our custom comparison function case_insensitive_compare() compares the lowercased versions of the given strings. The functools.cmp_to_key() function then converts this comparison function to a sorting key function, which we can pass to the sorted() function as the key argument.

Conclusion

In this blog, we've learned how to sort a list in Python using the built-in sorted() function and the sort() method. We also explored how to sort a list using custom sorting functions and comparison functions. With these tools, you can easily sort lists in your Python programs, making your code more organized and efficient.

Remember that the sorted() function is more versatile, as it works with any iterable and returns a new sorted list, while the sort() method only works with lists and sorts them in-place. Also, keep in mind that you can use the optional key argument to provide a custom sorting function or a custom comparison function (converted with functools.cmp_to_key()).

Now that you know how to sort lists in Python, you can apply this knowledge to other programming tasks, such as searching and filtering data, organizing output, or solving algorithmic problems. Happy coding!