Given a list of integers, the task is to find the N largest elements from it, assuming the list contains at least N elements.
Example:
Input: [4, 5, 1, 2, 9]
N = 2
Output: [9, 5]
Using heapq.nlargest()
The heapq module provides the nlargest() function which efficiently returns the N largest elements.
import heapq
l1 = [81, 52, 45, 10, 3, 2, 96]
print(heapq.nlargest(2, l1))
Output
[96, 81]
Explanation: heapq.nlargest(N, lst): internally builds a heap and retrieves the top N elements.
Using sorted()
sorted() function can sort the list in descending order and the first N elements of the result are the largest
l = [2, 1, 8, 7, 3, 0, 9, 4]
n = 3
res = sorted(l, reverse=True)[:n]
print(res)
Output
[9, 8, 7]
Explanation:
- sorted(l, reverse=True): returns a descending list.
- [:n]: retrieves the top N elements.
Using numpy.argsort()
The numpy library provides a vectorized way to find N largest elements using array sorting.
import numpy as np
l = [2, 6, 41, 85, 0, 3, 7, 6, 10]
n = 3
arr = np.array(l)
print(arr[np.argsort(arr)[-n:]])
Output
[10 41 85]
Explanation:
- np.argsort(arr): returns indices that would sort the array.
- [-n:]: selects indices of the N largest elements.
Using sort()
Sorting the list allows accessing the last N elements directly since the largest values appear at the end after sorting.
l = [1000, 298, 3579, 100, 200, -45, 900]
n = 4
l.sort()
print(l[-n:])
Explanation:
- l.sort(): arranges elements in ascending order.
- [-n:] retrieves the last N values, which are the largest.