Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to sort a list of tuples by second Item
When it is required to sort a list of tuples based on the second item, the lambda function and sorted() method can be used.
A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on). A list of tuples basically contains tuples enclosed in a list.
Anonymous function is a function which is defined without a name. In general, functions in Python are defined using def keyword, but anonymous function is defined with the help of lambda keyword. It takes a single expression, but can take any number of arguments. It uses the expression and returns the result of it.
The sorted() method is used to sort the elements of a list and returns a new sorted list without modifying the original.
Using Lambda Function with sorted()
Below is a demonstration for the same −
def tuple_sort(my_tuple):
return(sorted(my_tuple, key = lambda x: x[1]))
my_tuple = [('bill', 11), ('rick', 45), ('john', 89), ('liv', 25)]
print("The list of tuple is : ")
print(my_tuple)
print("After sorting, the list of tuple becomes : ")
print(tuple_sort(my_tuple))
The list of tuple is :
[('bill', 11), ('rick', 45), ('john', 89), ('liv', 25)]
After sorting, the list of tuple becomes :
[('bill', 11), ('liv', 25), ('rick', 45), ('john', 89)]
Alternative Method Using itemgetter
You can also use itemgetter from the operator module for better performance ?
from operator import itemgetter
data = [('apple', 25), ('banana', 12), ('orange', 45), ('grape', 8)]
sorted_data = sorted(data, key=itemgetter(1))
print("Original list:")
print(data)
print("Sorted by second element:")
print(sorted_data)
Original list:
[('apple', 25), ('banana', 12), ('orange', 45), ('grape', 8)]
Sorted by second element:
[('grape', 8), ('banana', 12), ('apple', 25), ('orange', 45)]
Sorting in Descending Order
To sort in descending order, use the reverse=True parameter ?
students = [('Alice', 85), ('Bob', 90), ('Charlie', 78), ('Diana', 92)]
sorted_desc = sorted(students, key=lambda x: x[1], reverse=True)
print("Sorted in descending order by marks:")
print(sorted_desc)
Sorted in descending order by marks:
[('Diana', 92), ('Bob', 90), ('Alice', 85), ('Charlie', 78)]
How It Works
- A function named
tuple_sortis defined, that takes a list of tuples as parameter. - The
lambda x: x[1]function extracts the second element (index 1) from each tuple. - The
sorted()function uses this key to compare and sort the tuples. - This returns a new sorted list without modifying the original.
Conclusion
Use lambda with sorted() for simple sorting by tuple elements. For better performance with large datasets, consider using itemgetter() from the operator module.
