- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple using Python program
When it is required to sort a list of tuples in increasing order based on last element of every tuple, a method is defined, that iterates over the tuple and performs a simple swap to achieve the same.
Below is the demonstration of the same −
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)]
A method named ‘sort_tuple’ is defined, that takes a list of tuple as parameter
It iterates through the list, and checks to see last element of every tuple in the list of tuple is greater or not.
A simple swap is used to put them in their right places.
The list of tuple is returned as output.
Outside the method, a list of tuple is defined, and is displayed on the console.
The method is called by passing this list of tuple.
The output is displayed on the console.
- Python program to Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple
- Sort Tuples in Increasing Order by any key in Python program
- Python program to sort tuples in increasing order by any key.
- Reverse each tuple in a list of tuples in Python
- Python program to sort a list of tuples by second Item
- Python program to Sort Tuples by their Maximum element
- Sort list of tuples by specific ordering in Python
- Python program to Order Tuples using external List
- Python program to sort a tuple by its float element
- Update each element in tuple list in Python
- Python program to sort a list of tuples alphabetically
- Create a list of tuples from given list having number and its cube in each tuple using Python
- Python Group by matching second tuple value in list of tuples
- Python program to create a list of tuples from the given list having the number and its cube in each tuple
- Filter Tuples by Kth element from List in Python