The list is a data structure that allows you to store multiple variables in a single variable. You can also store objects in it. You can create both single and 2Dimensional lists in Python. In this tutorial, you will learn how to Sort 2d Lists in Python.
Methods to Sort 2d Lists in Python
Method 1: Sorting 2D list using a Single Column
One of the simplest ways to sort a 2D list in Python is using a single column. Python provides you built-in sort() function that allows you to sort the list. Use the below example.
data = [[30, 20, 10], [60, 50, 40], [90, 80, 70]]
data.sort(key=lambda x: x[0])
In this code snippet, you have a 2D list called data. I want to sort it based on the values in the first column. By using the sort() function and specifying the key parameter as lambda x: x[0], you can achieve the desired sorting.
Method 2: Sorting on Multiple Columns
You can also sort a 2D list based on multiple columns. Python provides a powerful tool called the operator
module, which does this process. Below is the code for this method
import operator
data = [[30, 20, 10], [60, 50, 40], [90, 80, 70]]
data.sort(key=operator.itemgetter(0, 1))
Method 3: Sorting in Descending Order
By default, Python’s sort()
function sorts in ascending order. However, if you want to sort a 2D list in descending order, you can use the reverse
parameter.
data = [[30, 20, 10], [60, 50, 40], [90, 80, 70]]
data.sort(key=lambda x: x[0], reverse=True)
In this code snippet, you sorted the data
list based on the values in the first column. But in descending order. You can reverse-sort the list by setting the reverse
parameter to True
Method 4: Sorting with some Conditions
You can also sort a 2D list based on some conditions or criteria. Python allows you to define custom comparison functions to achieve this. Below is an example of it.
data = [[30, 20, 10], [60, 50, 40], [90, 80, 70]]
def custom_sort(item):
# Define the custom sorting logic here
return item[0] * item[1] - item[2]
data.sort(key=custom_sort)
In the above code snippet, you define a custom comparison function called custom_sort
that calculates a custom sorting metric. The sort()
function then uses this function as the key
parameter to sort the data
list accordingly.
Method 5: Sorting with the sorted() Function
Instead of the sort()
method, Python also provides the sorted()
function, which returns a new sorted list instead of modifying the original one. This can be useful when you want to preserve the original order.
data = [[30, 20, 10], [60, 50, 40], [90, 80, 70]]
sorted_data = sorted(data, key=lambda x: x[0])
In this code snippet, you used the sorted()
function with the same key
parameter to sort the data
list and store the sorted results in a new list called sorted_data
.
Conclusion
Sometimes it may become necessary to sort the list whether it is 1D or 2D. The above are the methods to quickly sort the 2D list in Python. You can use any method you like.
Leave a Reply