Python Program to Sort the list according to the column using lambda
We often need to organize data based on a particular value, such as sorting rows in a dataset by a column. Python makes this task simple by using the sorted()
function along with a lambda
function. In this article, we will explore various approaches to Sorting the list according to column.
Let's understand this with a basic example:
a = [(2, 'B'), (1, 'A'), (3, 'C')]
# Sort by the first column
b = sorted(a, key=lambda x: x[0])
print(b)
Output
[(1, 'A'), (2, 'B'), (3, 'C')]
Explanation:
lambda x: x[0]
selects the first element of each tuple to sort by.- The list is sorted in ascending order based on the first column.
Table of Content
Sort by First Column
To sort a list of lists or tuples by the first column (index 0), we can use the sorted() function with a lambda function as the sorting key.
a = [(3, 'fun!'), (1, 'Python'), (2, 'is')]
# Sort by first column (index 0)
sorted_data = sorted(a, key=lambda x: x[0])
print(sorted_data)
Output
[(1, 'Python'), (2, 'is'), (3, 'fun!')]
Explanation:
x[0]
extracts the first element of each tuple for sorting.- The list is sorted in ascending order by default.
Sort by Second Column
To sort a list of lists or tuples by the second column (index 1), we can use the sorted() function with a lambda function specifying the second element.
a = [(3, 'fun!'), (1, 'Python'), (2, 'is')]
# Sort by second column (index 1)
sorted_data = sorted(a, key=lambda x: x[1])
print(sorted_data)
Output
[(1, 'Python'), (3, 'fun!'), (2, 'is')]
Sort a List of Lists by a Specific Column
To sort a list of lists by a specific column (index) in Python, we can use the sorted()
function and specify the column index in the key
parameter using a lambda function.
a = [[3, 50], [1, 70], [2, 60]]
# Sort by second column (index 1)
sorted_data = sorted(a, key=lambda x: x[1])
print(sorted_data)
Output
[[3, 50], [2, 60], [1, 70]]
Explanation:
- The
lambda x: x[1]
extracts the second column values. - The list is sorted numerically by the second column.
Sort a list of tuple in Descending Order
We can use the sorted() function with the reverse=True parameter, and specify the column (or element) by which we want to sort using the key parameter (if necessary).
a = [(3, 'fun!'), (1, 'Python'), (2, 'is')]
# Sort by first column in descending order
sorted_data = sorted(a, key=lambda x: x[0], reverse=True)
print(sorted_data)
Output
[(3, 'fun!'), (2, 'is'), (1, 'Python')]
Explanation:
- The
reverse=True
argument sorts the data in descending order.