Python program to sort a list of tuples by second Item
Given a list of tuples, write a Python program to sort the tuples by the second item of each tuple.
Examples:
Input : [('for', 24), ('Geeks', 8), ('Geeks', 30)] Output : [('Geeks', 8), ('for', 24), ('Geeks', 30)] Input : [('452', 10), ('256', 5), ('100', 20), ('135', 15)] Output : [('256', 5), ('452', 10), ('135', 15), ('100', 20)]
Method #1: Using the Bubble Sort
Using the technique of Bubble Sort to we can perform the sorting. Note that each tuple is an element in the given list. Access the second element of each tuple using the nested loops. This performs the in-place method of sorting. The time complexity is similar to the Bubble Sort i.e. O(n^2).
Output:
[('Geeksforgeeks', 5), ('is', 10), ('a', 15), ('portal', 20), ('for', 24), ('Geeks', 28)]
Method #2: Using sort() method
While sorting via this method the actual content of the tuple is changed, and just like the previous method, the in-place method of the sort is performed.
Output:
[('akash', 5), ('rishav', 10), ('gaurav', 15), ('ram', 20)]
Method #3: Using sorted() method
Sorted() method sorts a list and always returns a list with the elements in a sorted manner, without modifying the original sequence. It takes three parameters from which two are optional, here we tried to use all of the three:
Iterable : sequence (list, tuple, string) or collection (dictionary, set, frozenset) or any other iterator that needs to be sorted.
Key(optional) : A function that would serve as a key or a basis of sort comparison.
Reverse(optional) : To sort this in ascending order we could have just ignored the third parameter, which we did in this program. If set true, then the iterable would be sorted in reverse (descending) order, by default it is set as false.
Output:
[('akash', 5), ('rishav', 10), ('gaurav', 15), ('ram', 20)]
No comments:
Post a Comment
Your feedback is highly appreciated and will help us to improve our content.