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
Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple using Python program
When working with lists of tuples, you often need to sort them based on the last element of each tuple. Python provides multiple approaches: using sorted() with a key function, the list.sort() method, or implementing a custom bubble sort algorithm.
Using sorted() with Key Function
The most Pythonic approach uses sorted() with a lambda function as the key ?
data = [(1, 92), (34, 25), (67, 89)]
print("Original tuple list:")
print(data)
# Sort by last element of each tuple
sorted_data = sorted(data, key=lambda x: x[-1])
print("Sorted list of tuples:")
print(sorted_data)
Original tuple list: [(1, 92), (34, 25), (67, 89)] Sorted list of tuples: [(34, 25), (67, 89), (1, 92)]
Using list.sort() Method
You can sort the list in-place using the sort() method ?
data = [(1, 92), (34, 25), (67, 89)]
print("Original tuple list:")
print(data)
# Sort in-place by last element
data.sort(key=lambda x: x[-1])
print("Sorted list of tuples:")
print(data)
Original tuple list: [(1, 92), (34, 25), (67, 89)] Sorted list of tuples: [(34, 25), (67, 89), (1, 92)]
Custom Bubble Sort Implementation
Here's a custom bubble sort function that compares the last elements ?
def sort_tuple(my_tup):
my_len = len(my_tup)
for i in range(0, my_len):
for j in range(0, my_len - i - 1):
if (my_tup[j][-1] > my_tup[j + 1][-1]):
temp = my_tup[j]
my_tup[j] = my_tup[j + 1]
my_tup[j + 1] = temp
return my_tup
my_tuple = [(1, 92), (34, 25), (67, 89)]
print("The tuple is:")
print(my_tuple)
print("The sorted list of tuples are:")
print(sort_tuple(my_tuple))
The tuple is: [(1, 92), (34, 25), (67, 89)] The sorted list of tuples are: [(34, 25), (67, 89), (1, 92)]
Comparison
| Method | Time Complexity | Modifies Original? | Best For |
|---|---|---|---|
sorted() |
O(n log n) | No | Most cases |
list.sort() |
O(n log n) | Yes | In-place sorting |
| Custom bubble sort | O(n²) | Yes | Educational purposes |
Conclusion
Use sorted(key=lambda x: x[-1]) for the most efficient and readable solution. The custom bubble sort approach is useful for understanding sorting algorithms but less efficient for production code.
Advertisements
