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 - Indices of atmost K elements in list
Next article icon

Python | Indices of N largest elements in list

Last Updated : 24 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes, while working with Python lists, we can have a problem in which we wish to find N largest elements. This task can occur in many domains such as web development and while working with Databases. We might sometimes, require to just find the indices of them. Let’s discuss a certain way to find indices of N largest elements in the list. 

Method 1: Using sorted() + lambda + list slicing This task can be performed using the combination of the above functions. In this, the sorted(), can be used to get the container in a way that requires getting N largest elements at the rear end, and then the indices can be computed using list slicing. 

Python3




# Python3 code to demonstrate working of
# Indices of N largest elements in list
# using sorted() + lambda + list slicing
 
# initialize list
test_list = [5, 6, 10, 4, 7, 1, 19]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initialize N
N = 4
 
# Indices of N largest elements in list
# using sorted() + lambda + list slicing
res = sorted(range(len(test_list)), key = lambda sub: test_list[sub])[-N:]
 
# printing result
print("Indices list of max N elements is : " + str(res))
 
 
Output
The original list is : [5, 6, 10, 4, 7, 1, 19] Indices list of max N elements is : [1, 4, 2, 6]

Time complexity: O(n log n) due to the sorting function used in the code.
Auxiliary space: O(n) as an additional list of indices is created to store the indices of the N largest elements.

Method 2: Using extend(),sort() and index() methods

Python3




# Python3 code to demonstrate working of
# Indices of N largest elements in list
 
# initialize list
test_list = [5, 6, 10, 4, 7, 1, 19]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initialize N
N = 4
 
# Indices of N largest elements in list
x = []
x.extend(test_list)
x.sort(reverse=True)
a = x[:N]
res = []
for i in a:
    res.append(test_list.index(i))
res.sort()
# printing result
print("Indices list of max N elements is : " + str(res))
 
 
Output
The original list is : [5, 6, 10, 4, 7, 1, 19] Indices list of max N elements is : [1, 2, 4, 6]

Time complexity: O(n*logn) where n is the length of the input list.
Auxiliary space: O(n), as the “x” and “res” lists have the same length as the input list, and the “a” list has a maximum length of N.

Method #3: Using heapq.nlargest()
The heapq library’s nlargest() function can be used to find the N largest elements in a list and then the index() method can be used to find the indices of those elements. Time complexity of this method is O(n log k) where n is the size of the list and k is the value of N. Space complexity is O(k) as we are storing the N largest elements in a heap.

Python3




# Python3 code to demonstrate working of
# Indices of N largest elements in list
# using heapq.nlargest()
 
# importing heapq
import heapq
 
# initialize list
test_list = [5, 6, 10, 4, 7, 1, 19]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initialize N
N = 4
 
# Indices of N largest elements in list
# using heapq.nlargest()
res = [test_list.index(i) for i in heapq.nlargest(N, test_list)]
 
# printing result
print("Indices list of max N elements is : " + str(res[::-1]))
 
#This code is contributed by Edula Vinay Kumar Reddy
 
 
Output
The original list is : [5, 6, 10, 4, 7, 1, 19] Indices list of max N elements is : [1, 4, 2, 6]

Time Complexity: O(n), where n is the length of the list test_list 
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list 

Method #4: Using itertools.islice()

Algorithm:

  1. Initialize the list and the value of N.
  2. Sort the list in decreasing order.
  3. Create an empty result list.
  4. Iterate through the original list and check if the element exists in the first N elements of the sorted list.
  5. If it exists, append its index to the result list.
  6. Return the result list.

Python3




# Python3 code to demonstrate working of
# Indices of N largest elements in list
import itertools
# initialize list
test_list = [5, 6, 10, 4, 7, 1, 19]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initialize N
N = 4
 
# Indices of N largest elements in list
sorted_list = sorted(test_list, reverse=True)
res = [i for i,x in enumerate(test_list) if x in itertools.islice(sorted_list, N)]
 
# printing result
print("Indices list of max N elements is : " + str(res))
 
 
Output
The original list is : [5, 6, 10, 4, 7, 1, 19] Indices list of max N elements is : [1, 2, 4, 6]

Time complexity: O(n log n) for sorting the list, followed by O(n) for iterating through the list and checking the existence of elements in the sorted list, resulting in a final time complexity of O(n log n).

Auxiliary Space: O(n) for the result list.



Next Article
Python - Indices of atmost K elements in list
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • 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
  • Get the Last Element of List in Python
    In this article, we will learn about different ways of getting the last element of a list in Python. For example, consider a list: Input: list = [1, 3, 34, 12, 6]Output: 6 Explanation: Last element of the list l in the above example is 6. Let's explore various methods of doing it in Python: 1. Using
    2 min read
  • Python program to find N largest elements from a list
    Given a list of integers, the task is to find N largest elements assuming size of list is greater than or equal o N. Examples : Input : [4, 5, 1, 2, 9] N = 2 Output : [9, 5] Input : [81, 52, 45, 10, 3, 2, 96] N = 3 Output : [81, 96, 52] A simple solution traverse the given list N times. In every tra
    5 min read
  • Python - Remove elements at Indices in List
    Given List, remove all the elements present in the indices list in Python. Input : test_list = [5, 6, 3, 7, 8, 1, 2, 10], idx_list = [2, 4, 5] Output : [5, 6, 7, 2, 10] Explanation : 3, 6, and 1 has been removed. Input : test_list = [5, 6, 3, 7, 8, 1, 2, 10], idx_list = [2] Output : [5, 6, 7, 8, 1,
    7 min read
  • Python | Get Last N Elements from Given List
    This article discusses ways to fetch the last N elements of a list in Python. Example: Using list Slicing [GFGTABS] Python test_list = [4, 5, 2, 6, 7, 8, 10] # initializing N N = 5 # using list slicing res = test_list[-N:] print(str(res)) [/GFGTABS]Output[2, 6, 7, 8, 10] Explaination: This problem c
    3 min read
  • Python - Elements Lengths in List
    Sometimes, while working with Python lists, can have problem in which we need to count the sizes of elements that are part of lists. This is because list can allow different element types to be its members. This kind of problem can have application in many domains such has day-day programming and we
    6 min read
  • Python - Duplicate Element Indices in List
    We are having a list we need to find the duplicate element indices. For example, we are given a list a = [10, 20, 30, 20, 40, 30, 50] we need to find indices of the duplicate items so that output should be {20: [1, 3], 30: [2, 5]}. Using a loop and a dictionaryWe iterate through the list using enume
    3 min read
  • Last Occurrence of Some Element in a List - Python
    We are given a list we need to find last occurrence of some elements in list. For example, w = ["apple", "banana", "orange", "apple", "grape"] we need to find last occurrence of string 'apple' so output will be 3 in this case. Using rindex()rindex() method in Python returns the index of the last occ
    3 min read
  • Python - K Maximum elements with Index in List
    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
    4 min read
  • Python - Minimum element indices
    Sometimes, while working with Python lists, we can have a problem in which we intend to find the position of minimum element of list. This task is easy and discussed many times. But sometimes, we can have multiple minimum elements and hence multiple minimum positions. Let’s discuss a shorthand to ac
    3 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