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
Selected Reading
Custom sorting in list of tuples in Python
Custom sorting in Python allows you to sort a list of tuples based on specific criteria using the sort() method with a key function. This is useful when you need to sort by a particular element within each tuple.
Basic Custom Sorting
The sort() method sorts elements in-place. Use the key parameter to specify which element of the tuple to sort by ?
def tuple_sort(my_tup):
my_tup.sort(key=lambda x: x[1])
return my_tup
my_tuple = [('Will', 100), ('John', 67), ('Harold', 86), ('Jane', 35)]
print("Original tuple:")
print(my_tuple)
print("Sorted by second element:")
print(tuple_sort(my_tuple))
Original tuple:
[('Will', 100), ('John', 67), ('Harold', 86), ('Jane', 35)]
Sorted by second element:
[('Jane', 35), ('John', 67), ('Harold', 86), ('Will', 100)]
Sorting by Different Elements
Sort by First Element (Name)
students = [('Will', 100), ('John', 67), ('Harold', 86), ('Jane', 35)]
# Sort by first element (name)
students.sort(key=lambda x: x[0])
print("Sorted by name:")
print(students)
Sorted by name:
[('Harold', 86), ('Jane', 35), ('John', 67), ('Will', 100)]
Sort in Descending Order
students = [('Will', 100), ('John', 67), ('Harold', 86), ('Jane', 35)]
# Sort by score in descending order
students.sort(key=lambda x: x[1], reverse=True)
print("Sorted by score (highest first):")
print(students)
Sorted by score (highest first):
[('Will', 100), ('Harold', 86), ('John', 67), ('Jane', 35)]
Using sorted() Function
Use sorted() to create a new sorted list without modifying the original ?
students = [('Will', 100), ('John', 67), ('Harold', 86), ('Jane', 35)]
# Create new sorted list
sorted_students = sorted(students, key=lambda x: x[1])
print("Original list:")
print(students)
print("New sorted list:")
print(sorted_students)
Original list:
[('Will', 100), ('John', 67), ('Harold', 86), ('Jane', 35)]
New sorted list:
[('Jane', 35), ('John', 67), ('Harold', 86), ('Will', 100)]
Comparison
| Method | Modifies Original? | Returns | Best For |
|---|---|---|---|
list.sort() |
Yes | None | When you want to modify the original list |
sorted() |
No | New sorted list | When you need to keep the original unchanged |
Conclusion
Use lambda functions with sort() or sorted() to customize tuple sorting. The key parameter specifies which tuple element to sort by, and reverse=True sorts in descending order.
Advertisements
