Open In App

Python program to sort a list of tuples by second Item

Last Updated : 13 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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). 

Python3




# Python program to sort a list of tuples by the second Item
 
# Function to sort the list of tuples by its second item
 
 
def Sort_Tuple(tup):
 
    # getting length of list of tuples
    lst = len(tup)
    for i in range(0, lst):
 
        for j in range(0, lst-i-1):
            if (tup[j][1] > tup[j + 1][1]):
                temp = tup[j]
                tup[j] = tup[j + 1]
                tup[j + 1] = temp
    return tup
 
 
# Driver Code
tup = [('for', 24), ('is', 10), ('Geeks', 28),
       ('Geeksforgeeks', 5), ('portal', 20), ('a', 15)]
 
print(Sort_Tuple(tup))


Output

[('Geeksforgeeks', 5), ('is', 10), ('a', 15), ('portal', 20), ('for', 24), ('Geeks', 28)]

Time Complexity: O(N2)
Auxiliary Space: O(1)

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. 

Python3




# Python program to sort a list of
# tuples by the second Item using sort()
 
# Function to sort the list by second item of tuple
def Sort_Tuple(tup):
 
    # reverse = None (Sorts in Ascending order)
    # key is set to sort using second element of
    # sublist lambda has been used
    tup.sort(key = lambda x: x[1])
    return tup
 
# Driver Code
tup = [('rishav', 10), ('akash', 5), ('ram', 20), ('gaurav', 15)]
 
# printing the sorted list of tuples
print(Sort_Tuple(tup))


Output

[('akash', 5), ('rishav', 10), ('gaurav', 15), ('ram', 20)]

Time Complexity: O(NlogN)
Auxiliary Space: O(1)

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. 

Python3




# Python program to sort a list of
# tuples by the second Item using sorted()
 
# Function to sort the list by second item of tuple
def Sort_Tuple(tup):
 
    # reverse = None (Sorts in Ascending order)
    # key is set to sort using second element of
    # sublist lambda has been used
    return(sorted(tup, key = lambda x: x[1])) 
 
# Driver Code
tup = [('rishav', 10), ('akash', 5), ('ram', 20), ('gaurav', 15)]
 
# printing the sorted list of tuples
print(Sort_Tuple(tup))


Output

[('akash', 5), ('rishav', 10), ('gaurav', 15), ('ram', 20)]

Time Complexity: O(NlogN)
Auxiliary Space: O(1)

Method 4: Using the itemgetter function from the operator module

The itemgetter function is a function from the operator module that allows you to specify which element in a tuple you want to sort by. In the example above, the itemgetter(1) function tells the sorted function to sort the tuples by the second element in each tuple (since indices start at 0, the second element has index 1).

Here is an example of how you can use itemgetter to sort a list of tuples by the first element instead:

Python3




from operator import itemgetter
 
def sort_tuples(tuples):
    # Sort the tuples by the second item using the itemgetter function
    return sorted(tuples, key=itemgetter(1))
 
# Test the function
tuples = [('for', 24), ('Geeks', 8), ('Geeks', 30)]
print(sort_tuples(tuples))
#This code is contributed by Edula Vinay Kumar Reddy


Output

[('Geeks', 8), ('for', 24), ('Geeks', 30)]

Time Complexity: O(NlogN)
Auxiliary Space: O(1)

Method 5: Using numpy.argsort() function

note: install numpy module using command “pip install numpy”

Here’s how to sort a list of tuples by the second item using numpy.argsort() function:

Algorithm:

Convert the input list of tuples to a numpy array with data type (object, int).
Use np.argsort to get the indices that would sort the numpy array based on the second column.
Use the resulting indices to sort the numpy array.
Convert the sorted numpy array back to a list of tuples.

Python3




import numpy as np
 
def sort_tuple(tup):
    # convert the list of tuples to a numpy array with data type (object, int)
    arr = np.array(tup, dtype=[('col1', object), ('col2', int)])
    # get the indices that would sort the array based on the second column
    indices = np.argsort(arr['col2'])
    # use the resulting indices to sort the array
    sorted_arr = arr[indices]
    # convert the sorted numpy array back to a list of tuples
    sorted_tup = [(row['col1'], row['col2']) for row in sorted_arr]
    return sorted_tup
 
# Driver code
tup = [('for', 24), ('is', 10), ('Geeks', 28),
       ('Geeksforgeeks', 5), ('portal', 20), ('a', 15)]
print(sort_tuple(tup))


Output:

[(‘Geeksforgeeks’, 5), (‘is’, 10), (‘a’, 15), (‘portal’, 20), (‘for’, 24), (‘Geeks’, 28)]
Time complexity:
The time complexity of this code is O(nlogn), where n is the length of the input list of tuples. This is because the np.argsort function has a time complexity of O(nlogn), and the other operations in the code take O(n) time.

Auxiliary Space:
The space complexity of this code is O(n), where n is the length of the input list of tuples. This is because the code creates a numpy array of size n to store the input list of tuples, and then creates another numpy array of size n to store the sorted array. The additional space used by other variables and operations is negligible compared to the size of the numpy arrays.



Similar Reads

Python program to find Tuples with positive elements in List of tuples
Given a list of tuples. The task is to get all the tuples that have all positive elements. Examples: Input : test_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, -6)] Output : [(4, 5, 9)] Explanation : Extracted tuples with all positive elements. Input : test_list = [(-4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, -6)] Output : [] Explanation : No tuple wit
10 min read
Python program to find tuples which have all elements divisible by K from a list of tuples
Given a list of tuples. The task is to extract all tuples which have all elements divisible by K. Input : test_list = [(6, 24, 12), (60, 12, 6), (12, 18, 21)], K = 6 Output : [(6, 24, 12), (60, 12, 6)] Explanation : Both tuples have all elements multiple of 6. Input : test_list = [(6, 24, 12), (60, 10, 5), (12, 18, 21)], K = 5 Output : [(60, 10, 5)
7 min read
Python | Remove duplicate tuples from list of tuples
Given a list of tuples, Write a Python program to remove all the duplicated tuples from the given list. Examples: Input : [(1, 2), (5, 7), (3, 6), (1, 2)] Output : [(1, 2), (5, 7), (3, 6)] Input : [('a', 'z'), ('a', 'x'), ('z', 'x'), ('a', 'x'), ('z', 'x')] Output : [('a', 'z'), ('a', 'x'), ('z', 'x')] Method #1 : List comprehension This is a naive
5 min read
Python | Find the tuples containing the given element from a list of tuples
Given a list of tuples, the task is to find all those tuples containing the given element, say n. Examples: Input: n = 11, list = [(11, 22), (33, 55), (55, 77), (11, 44)] Output: [(11, 22), (11, 44)] Input: n = 3, list = [(14, 3),(23, 41),(33, 62),(1, 3),(3, 3)] Output: [(14, 3), (1, 3), (3, 3)] There are multiple ways we can find the tuples contai
6 min read
Python | Remove tuples from list of tuples if greater than n
Given a list of a tuple, the task is to remove all the tuples from list, if it's greater than n (say 100). Let's discuss a few methods for the same. Method #1: Using lambda STEPS: Initialize a list of tuples: ini_tuple = [('b', 100), ('c', 200), ('c', 45), ('d', 876), ('e', 75)]Print the initial list: print("intial_list", str(ini_tuple))Define the
6 min read
Python | Remove tuples having duplicate first value from given list of tuples
Given a list of tuples, the task is to remove all tuples having duplicate first values from the given list of tuples. Examples: Input: [(12.121, 'Tuple1'), (12.121, 'Tuple2'), (12.121, 'Tuple3'), (923232.2323, 'Tuple4')] Output: [(12.121, 'Tuple1'), (923232.2323, 'Tuple4')]Input: [('Tuple1', 121), ('Tuple2', 125), ('Tuple1', 135), ('Tuple4', 478)]
7 min read
Python | Count tuples occurrence in list of tuples
Many a time while developing web and desktop products in Python, we use nested lists and have several queries about how to find the count of unique tuples. Let us see how to get the count of unique tuples in the given list of tuples. Below are some ways to achieve the above task. Method #1: Using Iteration C/C++ Code # Python code to count unique #
5 min read
Python | Combining tuples in list of tuples
Sometimes, we might have to perform certain problems related to tuples in which we need to segregate the tuple elements to combine with each element of complex tuple element( such as list ). This can have application in situations we need to combine values to form a whole. Let's discuss certain ways in which this can be performed. Method #1: Using
7 min read
Python | Convert string tuples to list tuples
Sometimes, while working with Python we can have a problem in which we have a list of records in form of tuples in stringified form and we desire to convert them to a list of tuples. This kind of problem can have its occurrence in the data science domain. Let's discuss certain ways in which this task can be performed. Method 1 (Using eval() + list
4 min read
Python - Filter all uppercase characters Tuples from given list of tuples
Given a Tuple list, filter tuples that contain all uppercase characters. Input : test_list = [("GFG", "IS", "BEST"), ("GFg", "AVERAGE"), ("GfG", ), ("Gfg", "CS")] Output : [('GFG', 'IS', 'BEST')] Explanation : Only 1 tuple has all uppercase Strings. Input : test_list = [("GFG", "iS", "BEST"), ("GFg", "AVERAGE"), ("GfG", ), ("Gfg", "CS")] Output : [
8 min read