
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 −
Example
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))
Output
The tuple is : [(1, 92), (34, 25), (67, 89)] The sorted list of tuples are : [(34, 25), (67, 89), (1, 92)]
Explanation
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.
- Related Articles
- 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 Order Tuples using external List
- Python program to Sort Tuples by their Maximum element
- Sort list of tuples by specific ordering in Python
- Python program to sort a tuple by its float element
- Create a list of tuples from given list having number and its cube in each tuple using Python
- Python program to sort a list of tuples alphabetically
- Python Program to Sort A List Of Names By Last Name
- Python Group by matching second tuple value in list of tuples
- Update each element in tuple list in Python
- Python program to create a list of tuples from the given list having the number and its cube in each tuple

Advertisements