Python sort tuples by second element: Tuples are a type of variable that allows you to store multiple items in a single variable. Tuple is one of four built-in data types in Python that are used to store data collections. The other three are List, Set, and Dictionary, all of which have different qualities and applications. A tuple is a collection that is both ordered and immutable.
The task is to write a Python program that sorts tuples by the second item in each tuple given a list of tuples.
Examples:
Input:
giventuple = [('Hello', 400), ('this', 500), ('is', 200), ('BTechGeeks', 100)]
Output:
[('BTechGeeks', 100), ('is', 200), ('Hello', 400), ('this', 500)]
- Python Program to Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple
- Python : How to Find an Element in Tuple by Value
- Python Program to Sort a List According to the Length of the Elements
Python program for Sorting a List of Tuples by the Second item
1)Key Function
When sorting a list, all of the list’s elements are compared to one another. However, before comparing the entries, it will call the key function on each entry to determine which portion of the object will be compared.
In other words, when an element is passed to the key function, it returns the element that should be used to compare the elements in the list while sorting.
2)Using lambda function
To sort a list of tuples by the second or ith item, we must include our custom comparator, i.e. key function, in the sort () function.
We use lambda function as key function.
Below is the implementation:
# given tuple giventuple = [('Hello', 400), ('this', 500), ('is', 200), ('BTechGeeks', 100)] # using lambda function giventuple.sort(key=lambda elem: elem[1]) # print giventuple print(giventuple)
Output:
[('BTechGeeks', 100), ('is', 200), ('Hello', 400), ('this', 500)]
3)Using custom function as comparator
First, create a function that accepts a tuple and returns the second element.
Below is the implementation:
def comparator(elementtuple): return elementtuple[1] # given tuple giventuple = [('Hello', 400), ('this', 500), ('is', 200), ('BTechGeeks', 100)] # using lambda function giventuple.sort(key=comparator) # print giventuple print(giventuple)
Output:
[('BTechGeeks', 100), ('is', 200), ('Hello', 400), ('this', 500)]
Related Programs:
- python program to sort a list of tuples in increasing order by the last element in each tuple
- python how to find all indexes of an item in a list
- python how to sort a list of strings list sort
- python program to create a list of tuples with the first element as the number and second element as the square of the number
- cpp how to sort a list of objects with custom comparator or lambda function
- how to create and initialize a list of lists in python
- python how to sort a dictionary by key or value