How To Sort A Multidimensional List In Python

In this tutorial, we will learn how to sort a multidimensional list in Python. Sorting a multidimensional list, also known as a nested list or a list of lists, can prove to be quite challenging at times.

However, it is useful because it allows you to represent complex data structures, such as tables and matrices, in a readable and manageable way. Our aim is to break down the process into simple and actionable steps to make it easier for you to understand and implement it in your own projects.

Step 1: Understanding Multidimensional Lists

A multidimensional list is essentially a list that contains one or more sub-lists. For example, consider the following 2-dimensional list (list of lists):

The structure of the list comprises three lists, each containing three integers.

Step 2: Sorting the List by Columns

Python provides several built-in functions and methods to help with sorting lists. In this case, we will use the sorted() function, which returns a new sorted list from the elements of the given iterable. We will utilize the key argument of the function, in which we will define a lambda function to sort the list by columns.

Here’s what the code looks like:

The output will be:

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

The lists have been sorted according to the second column (index 1) values.

Step 3: Sorting the List by Rows

Now let’s sort the elements of each row in the list. We’ll use a list comprehension to apply the sorted() function to each row individually.

The output will be:

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

As you can see, each row has been sorted individually.

Full Code

Output:

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

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

Conclusion

Sorting a multidimensional list in Python might seem complicated at first. However, using the right combination of built-in functions and methods, like the sorted() function and list comprehensions, we can easily sort nested lists by columns and rows. This tutorial demonstrates how to use these tools to effectively work with multidimensional lists in your own Python projects.