Python - Sort Records by Kth Index List
Last Updated :
16 May, 2023
Sometimes, while working with Python Records, we can have a problem in which we need to perform Sorting of Records by some element in Tuple, this can again be sometimes, a list and sorting has to performed by Kth index of that list. This is uncommon problem, but can have usecase in domains such as web development. Let's discuss certain way in which this task can be performed.
Input : test_list = [([4, 5], 'Gfg'), ([8, 4], 'is'), ([2, 3], 'best')]
K = 0
Output : [([2, 3], 'best'), ([4, 5], 'Gfg'), ([8, 4], 'is')]
Input : test_list = [([4, 5], 'Gfg'), ([8, 4], 'is'), ([2, 3], 'best')]
K = 1
Output : [([2, 3], 'best'), ([8, 4], 'is'), ([4, 5], 'Gfg')]
Method 1: Using sort() + lambda
The combination of above functions can be used to solve this problem. In this, we perform the task of sorting using sort, the parameter and index by which sorting has to be performed is provided using lambda function.
Python3
# Python3 code to demonstrate working of
# Sort Records by Kth Index List
# Using sort() + lambda
# initializing list
test_list = [([4, 5, 7, 3], 'Gfg'), ([8, 6, 3, 1], 'is'),
([2, 3, 5, 2], 'best')]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 1
# Sort Records by Kth Index List
# Using sort() + lambda
test_list.sort(key = lambda sub: sub[0][K])
# printing result
print("The records after sorting : " + str(test_list))
Output :
The original list is : [([4, 5, 7, 3], 'Gfg'), ([8, 6, 3, 1], 'is'), ([2, 3, 5, 2], 'best')]
The records after sorting : [([2, 3, 5, 2], 'best'), ([4, 5, 7, 3], 'Gfg'), ([8, 6, 3, 1], 'is')]
Time Complexity: O(nlogn) where n is the number of elements in the in the list “test_list”. The sort() + lambda is used to perform the task and it takes O(nlogn) time.
Auxiliary Space: O(1) additional space is not required.
Method #2: Using itemgetter() from the operator module
The operator module provides a function itemgetter() that is an efficient alternative to lambda functions when sorting a list of tuples. This function can be used to extract the Kth index element from the sublists in the main list.
Python3
# import the operator module
import operator
# initializing list
test_list = [([4, 5, 7, 3], 'Gfg'), ([8, 6, 3, 1], 'is'), ([2, 3, 5, 2], 'best')]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 1
# Sort Records by Kth Index List
# Using itemgetter() from operator module
test_list.sort(key=operator.itemgetter(0, K))
# printing result
print("The records after sorting : " + str(test_list))
OutputThe original list is : [([4, 5, 7, 3], 'Gfg'), ([8, 6, 3, 1], 'is'), ([2, 3, 5, 2], 'best')]
The records after sorting : [([2, 3, 5, 2], 'best'), ([4, 5, 7, 3], 'Gfg'), ([8, 6, 3, 1], 'is')]
Time complexity: Both the approaches have a time complexity of O(nlogn) as sorting the list takes O(nlogn) time.
Auxiliary space: Both the approaches use O(1) extra space as no extra data structure is used for the sorting algorithm.
Method #3: Using a custom function to sort the list
- Initialize the list of records.
- Define a function that takes a single record as input and returns the value of the Kth index of the list in the record.
- Use the sorted() function to sort the list based on the Kth index value obtained by calling the custom function for each record in the list.
- Print the sorted list.
Python3
# initializing list
test_list = [([4, 5, 7, 3], 'Gfg'), ([8, 6, 3, 1], 'is'), ([2, 3, 5, 2], 'best')]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 1
# define custom function to extract Kth index value
def get_kth_index(record):
return record[0][K]
# sort records by Kth index list using custom function
sorted_list = sorted(test_list, key=get_kth_index)
# print result
print("The records after sorting : " + str(sorted_list))
OutputThe original list is : [([4, 5, 7, 3], 'Gfg'), ([8, 6, 3, 1], 'is'), ([2, 3, 5, 2], 'best')]
The records after sorting : [([2, 3, 5, 2], 'best'), ([4, 5, 7, 3], 'Gfg'), ([8, 6, 3, 1], 'is')]
Time complexity: O(n log n) (where n is the number of records in the list) because of the sorting operation.
Auxiliary space: O(n) (where n is the number of records in the list) to store the sorted list.
Similar Reads
Python - Sort from Kth index in List
Given a list of elements, perform sort from Kth index of List. Input : test_list = [7, 3, 7, 6, 4, 9], K = 2 Output : [7, 3, 4, 6, 7, 9] Explanation : List is unsorted till 3 (1st index), From 2nd Index, its sorted. Input : test_list = [5, 4, 3, 2, 1], K= 3 Output : [5, 4, 3, 1, 2] Explanation : Onl
3 min read
Python - Group records by Kth column in List
Sometimes, while working with Python lists, we can have a problem in which we need to perform grouping of records on basis of certain parameters. One such parameters can be on the Kth element of Tuple. Lets discuss certain ways in which this task can be performed. Method #1 : Using loop + defaultdic
8 min read
Sort a list in python
Sorting is a fundamental operation in programming, allowing you to arrange data in a specific order. Here is a code snippet to give you an idea about sorting.Python# Initializing a list a = [5, 1, 5, 6] # Sort modifies the given list a.sort() print(a) b = [5, 2, 9, 6] # Sorted does not modify the gi
5 min read
Python - Sort row by K multiples
Given a Matrix, perform row sorting by number of multiple of K present in row. Input : test_list = [[3, 4, 8, 1], [12, 32, 4, 16], [1, 2, 3, 4], [9, 7, 5]], K = 4 Output : [[9, 7, 5], [1, 2, 3, 4], [3, 4, 8, 1], [12, 32, 4, 16]] Explanation : 0 < 1 < 2 < 4, multiple of 4 occurrence order. I
3 min read
Sort a List of Tuples by Second Item - Python
The task of sorting a list of tuples by the second item is common when working with structured data in Python. Tuples are used to store ordered collections and sometimes, we need to sort them based on a specific element, such as the second item. For example, given the list [(1, 3), (4, 1), (2, 2)],
2 min read
Python - Reverse Row sort in Lists of List
We are given a list of lists where each inner list represents a row and our task is to sort each row in descending order while keeping the overall structure intact. For example, given a = [[5, 2, 8], [9, 1, 4], [6, 7, 3]], after sorting each row in reverse order, the result will be [[8, 5, 2], [9, 4
3 min read
Python - Records with Value at K index
Sometimes, while working with records, we might have a problem in which we need to find all the tuples of elements for a particular value at a particular Kth position of tuple. This seems to be a peculiar problem but while working with many keys in records, we encounter this problem. Letâs discuss c
8 min read
Python | Minimum K records of Nth index in tuple list
Sometimes, while working with data, we can have a problem in which we need to get the minimum of elements filtered by the Nth element of record. This has a very important utility in web development domain. Letâs discuss certain ways in which this task can be performed. Method #1 : Using filter() + l
9 min read
Python - Sort Dictionary List by Key's ith Index value
Given List of dictionaries, sort dictionaries on basis of Key's ith index value Input : [{"Gfg" : "Best", "for" : "Geeks"}, {"Gfg" : "Good", "for" : "Me"}, {"Gfg" : "Better", "for" : "All"}], K = "Gfg", i = 1 Output : [{'Gfg': 'Best', 'for': 'Geeks'}, {'Gfg': 'Better', 'for': 'All'}, {'Gfg': 'Good',
7 min read
Python - Find minimum k records from tuple list
Sometimes, while working with data, we can have a problem in which we have records and we require to find the lowest K scores from it. This kind of application is popular in web development domain. Letâs discuss certain ways in which this problem can be solved. Method #1 : Using sorted() + lambda Th
6 min read