Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Every Kth index Maximum in List
Next article icon

Python – K Maximum elements with Index in List

Last Updated : 23 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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))
 
 
Output
The 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))
 
 
Output
The 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

  1. Import the heapq module.
  2. Initialize a heap with the first K elements of the list.
  3. 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.
  4. Once all elements have been processed, the heap will contain the K maximum elements.
  5. For each element in the heap, find its index in the original list using the index() method.
  6. Combine the index and the element as a tuple, and add it to the result list.
  7. 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))
 
 
Output
The 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.



Next Article
Python - Every Kth index Maximum in List
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

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
    5 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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences