
- 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
Python program to sort tuples in increasing order by any key.
Given a tuple, our task is to sort the list of tuples in increasing order by any key in a tuple. We need to sort them according to any given key.to do this here we use sorted() function where we sort them using key=last and store last as the key index according to which we have to sort the given tuples.
Example
Input: A = [(2, 55), (1, 20), (4, 40), (2, 30)] k = 0 Output: [(1, 20), (2, 30), (2, 55), (4, 40)]
Explanation
Increasing Sorted order using the 0th index key.
Algorithm
Step 1: get the last key value. Step 2: next we use inbuilt function sorted () method where we sort them using key=last and store last as the key index according to which we have to sort the given tuples. Step 3: display sorted list.
Example Code
# Python program to sort a list of tuples # in increasing order by any key # get the last key. def data(n): return n[k] # function to sort the tuple def tuplesort(tup): # We pass used defined function last # As a parameter. return sorted(tup, key = data) # Driver code a = [(230, 456, 120), (205, 414, 39), (89, 410, 213)] k = int(input("Enter the Index ::>")) print("Sorted:"), print(tuplesort(a))
Output
Enter the Index ::>2 Sorted: [(205, 414, 39), (230, 456, 120), (89, 410, 213)]
- Related Articles
- Sort Tuples in Increasing Order by any key in Python program
- Python program to Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple
- Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple using Python program
- Python program to Sort Tuples by their Maximum element
- Program to sort array by increasing frequency of elements in Python
- Python program to sort a list of tuples by second Item
- Python program to sort tuples by frequency of their absolute difference
- Sort Tuples by Total digits in Python
- Python – Sort Tuples by Total digits
- Program to sort all even and odd numbers in increasing and decreasing order respectively in Python
- Python program to Order Tuples using external List
- Python program to sort a list of tuples alphabetically
- JavaScript Program to Count rotations required to sort given array in non-increasing order
- Sort list of tuples by specific ordering in Python
- Python program to sort string in custom order

Advertisements