Python - K Maximum elements with Index in List
Last Updated :
23 Apr, 2023
GIven a List, extract K Maximum elements with their indices.
Input : test_list = [5, 3, 1, 4, 7, 8, 2], K = 2 Output : [(4, 7), (5, 8)] Explanation : 8 is maximum on index 5, 7 on 4th. Input : test_list = [5, 3, 1, 4, 7, 10, 2], K = 1 Output : [(5, 10)] Explanation : 10 is maximum on index 5.
Method #1 : Using sorted() + index()
The combination of above functions provide a way of finding solution to this problem. In this, we initially perform sort and extract K maximum elements, then are encapsulated in tuple with their ordering in original list.
Python3
# Python3 code to demonstrate working of
# K Maximum elements with Index in List
# Using sorted() + index()
# initializing list
test_list = [5, 3, 1, 4, 7, 8, 2]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 3
# Using sorted() + index()
# using sorted() to sort and slice K maximum elements
temp = sorted(test_list)[-K:]
res = []
for ele in temp:
# encapsulating elements with index using index()
res.append((test_list.index(ele), ele))
# printing result
print("K Maximum with indices : " + str(res))
OutputThe original list : [5, 3, 1, 4, 7, 8, 2]
K Maximum with indices : [(0, 5), (4, 7), (5, 8)]
Time Complexity: O(nlogn), where n is the elements of list
Auxiliary Space: O(n), where n is the size of list
Method #2 : Using enumerate() + itemgetter()
The combination of above functions can be used to solve this problem. In this, we perform the task of getting indices using enumerate() and itemgetter() is used to get the elements.
Python3
# Python3 code to demonstrate working of
# K Maximum elements with Index in List
# Using enumerate() + itemgetter()
from operator import itemgetter
# initializing list
test_list = [5, 3, 1, 4, 7, 8, 2]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 3
# Using enumerate() + itemgetter()
# Making index values pairs at 1st stage
res = list(sorted(enumerate(test_list), key = itemgetter(1)))[-K:]
# printing result
print("K Maximum with indices : " + str(res))
OutputThe original list : [5, 3, 1, 4, 7, 8, 2]
K Maximum with indices : [(0, 5), (4, 7), (5, 8)]
Time Complexity: O(n) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n) where n is the number of elements in the list “test_list”.
Method 3 : using the heapq module in Python.
step-by-step approach
- Import the heapq module.
- Initialize a heap with the first K elements of the list.
- Traverse the remaining elements of the list and for each element, compare it with the smallest element in the heap. If the element is greater than the smallest element, replace the smallest element with the current element.
- Once all elements have been processed, the heap will contain the K maximum elements.
- For each element in the heap, find its index in the original list using the index() method.
- Combine the index and the element as a tuple, and add it to the result list.
- Return the result list.
Python3
import heapq
# initializing list
test_list = [5, 3, 1, 4, 7, 8, 2]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 3
# using heapq module
heap = test_list[:K]
heapq.heapify(heap)
for i in range(K, len(test_list)):
if test_list[i] > heap[0]:
heapq.heappop(heap)
heapq.heappush(heap, test_list[i])
# finding indices of K maximum elements
res = []
for elem in heap:
index = test_list.index(elem)
res.append((index, elem))
# printing result
print("K Maximum with indices : " + str(res))
OutputThe original list : [5, 3, 1, 4, 7, 8, 2]
K Maximum with indices : [(0, 5), (4, 7), (5, 8)]
The time complexity of this approach is O(n log K), where n is the length of the list and K is the number of maximum elements to be found.
The auxiliary space used by this approach is O(K), as we are only storing K elements in the heap at any given time.
Similar Reads
Python - Elements Maximum till current index in List Given list with elements, extract element if it's the maximum element till current index. Input : test_list = [4, 6, 7, 8] Output : [4, 6, 7, 8] Explanation : All elements are maximum till their index. Input : test_list = [6, 7, 3, 6, 8, 7] Output : [7, 8] Explanation : 7 and 8 are maximum till thei
7 min read
Python - Assign keys with Maximum element index Given Dictionary with value lists, the task is to write a Python program to assign each key with an index of the maximum value in the value list. Examples: Input : test_dict = {"gfg" : [5, 3, 6, 3], "is" : [1, 7, 5, 3], "best" : [9, 1, 3, 5]} Output : {'gfg': 2, 'is': 1, 'best': 0} Explanation : Max
4 min read
Python - Every Kth index Maximum in List We generally wish to employ a particular function to all the elements in a list. But sometimes, according to requirement we would wish to employ a particular functionality to certain elements of the list, basically to every Kth element in list. Letâs discuss certain ways in which maximum of these el
4 min read
Python | Maximum element in tuple list Sometimes, while working with data in form of records, we can have a problem in which we need to find the maximum element of all the records received. This is a very common application that can occur in Data Science domain. Letâs discuss certain ways in which this task can be performed. Method #1: U
6 min read
Python - Key with Maximum element at Kth index in Dictionary Value List Given a dictionary with values as lists, the task is to write a Python program to get the key with the maximum element at the Kth index by comparing the elements of each list. Input : test_dict = {'Gfg' : [4, 6, 8, 2], 'is' : [1, 4, 5, 9], 'best' :[2, 3, 4, 10], 'for' :[4, 5, 2, 1], 'geeks' :[2, 10,
8 min read
Python - Maximum of K element in other list Given two lists, extract maximum of elements with similar K in corresponding list. Input : test_list1 = [4, 3, 6, 2, 8], test_list2 = [3, 6, 3, 4, 3], K = 3 Output : 8 Explanation : Elements corresponding to 3 are, 4, 6, and 8, Max. is 8. Input : test_list1 = [10, 3, 6, 2, 8], test_list2 = [5, 6, 5,
4 min read
Python - Ranged Maximum Element in String List Sometimes, while working with Python data, we can have a problem in which we have data in form of String List and we require to find the maximum element in that data, but that also in a certain range of indices. This is quite peculiar problem but can have application in data domains. Let's discuss c
4 min read
Python - Maximum element in Cropped List Sometimes, while working with Python, we can have a problem in which we need to get maximum of list. But sometimes, we need to get this for between custom indices. This can be need of any domain be it normal programming or web development. Let's discuss certain ways in which this task can be perform
4 min read
Python | Positions of maximum element in list Sometimes, while working with Python lists, we can have a problem in which we intend to find the position of maximum element of list. This task is easy and discussed many times. But sometimes, we can have multiple maximum elements and hence multiple maximum positions. Let's discuss a shorthand to ac
3 min read
Python - Indices of atmost K elements in list Many times we might have problem in which we need to find indices rather than the actual numbers and more often, the result is conditioned. First approach coming to mind can be a simple index function and get indices less than or equal than particular number, but this approach fails in case of dupli
7 min read