Python | Indices of N largest elements in list
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 certain way to find indices of N largest elements in list.
Method : Using sorted() + lambda + list slicing
This task can be performed using the combination of above functions. In this the sorted(), can be used to get the container in way which requires to get N largest elements at rear end and then the indices can be computed using list slicing.
# 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)) |
The original list is : [5, 6, 10, 4, 7, 1, 19] Indices list of max N elements is : [1, 4, 2, 6]
Recommended Posts:
- Python | Indices of sorted list of list elements
- Python | Find elements of a list by indices
- Python | Group elements at same indices in a multi-list
- Python program to find N largest elements from a list
- Python | Indices list of matching element from other list
- Python | Ways to find indices of value in list
- Python | Duplicate element indices in list
- Python | Find indices with None values in given list
- Python | Get indices of True values in a binary list
- Python program to fetch the indices of true values in a Boolean list
- Python | Merge List with common elements in a List of Lists
- Python | Sorting list of lists with similar list elements
- Python | Replace elements in second list with index of same element in first list
- Python | Add list elements with a multi-list based on index
- Python | Largest number possible from list of given numbers
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



