Python sort tuples by second element – Python: How to Sort a List of Tuples by second Item

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 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: