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):

1 2 3 4 5 |
multidimensional_list = [ [3, 4, 1], [1, 2, 9], [7, 5, 8] ] |

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:

1 2 3 4 5 6 7 8 9 10 11 |
multidimensional_list = [ [3, 4, 1], [1, 2, 9], [7, 5, 8] ] # Sort the multidimensional list by cth column cth_column = 1 sorted_list = sorted(multidimensional_list, key=lambda row: row[cth_column]) print(sorted_list) |

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.

1 2 3 |
sorted_rows = [sorted(row) for row in multidimensional_list] print(sorted_rows) |

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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
multidimensional_list = [ [3, 4, 1], [1, 2, 9], [7, 5, 8] ] # Sort the multidimensional list by cth column cth_column = 1 sorted_list = sorted(multidimensional_list, key=lambda row: row[cth_column]) print(sorted_list) # Sort the elements of each row sorted_rows = [sorted(row) for row in multidimensional_list] print(sorted_rows) |

## 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.