
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 Questions & Answers
- 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
- Sort Tuples by Total digits in Python
- Python program to sort a list of tuples by second Item
- Python program to sort tuples by frequency of their absolute difference
- Python – Sort Tuples by Total digits
- Python program to Order Tuples using external List
- Sort list of tuples by specific ordering in Python
- Sort Python Dictionaries by Key or Value
- Program to sort all even and odd numbers in increasing and decreasing order respectively in Python
- Python program to sort a list of tuples alphabetically
- Implementing insertion sort to sort array of numbers in increasing order using JavaScript
Advertisements