How to Sort a 2d List in Python

In this tutorial, we’ll explore how to sort a 2D list in Python. Sorting is an essential tool in programming that can help in analyzing and summarizing data. Python provides several built-in techniques and methods to sort data, including sorting two-dimensional lists, also known as nested lists.

Step 1: Understanding a 2D List

In Python, a 2D list is simply a list that contains other lists as its elements. For example:

This is a 2D list with 3 rows and 3 columns. As with regular lists, you can manipulate 2D lists using various Python methods.

Step 2: Effective Methods to Sort a 2D List

The ability to sort data in Python can be achieved through a variety of methods, such as the built-in sort() and the sorted() methods.

The sort() method is a built-in Python method that sorts the list in ascending order by default. To use it to sort a 2D list, you’ll need to specify the index of the inner list to base the sorting on in its key parameter.

On the other hand, the sorted() function can be used to achieve the same result but does not modify the original list. Instead, it returns a new list that is sorted.

Here’s an example of how to use both methods:

Full code

Output

Sorted using sort(): [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Sorted using sorted(): [[3, 6, 9], [1, 4, 7], [2, 5, 8]]

Conclusion

Sorting 2D lists in Python is a crucial skill when working with data. By understanding the built-in Python methods like sort() and sorted(), you can correctly sort a nested list based on specific columns easily. Now you’re ready to organize and better analyze your data.

Remember, the key to mastering Python (or any programming language) lies in consistent practice. For more tutorials to enhance your Python skills, check out the Python official documentation.