Python program to find N largest elements from a list (original) (raw)

Last Updated : 12 Nov, 2025

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.

Python `

import heapq l1 = [81, 52, 45, 10, 3, 2, 96] print(heapq.nlargest(2, l1))

`

**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

Python `

l = [2, 1, 8, 7, 3, 0, 9, 4] n = 3

res = sorted(l, reverse=True)[:n] print(res)

`

**Explanation:

Using numpy.argsort()

The numpy library provides a vectorized way to find N largest elements using array sorting.

Python `

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:]])

`

**Explanation:

Using sort()

Sorting the list allows accessing the last N elements directly since the largest values appear at the end after sorting.

Python `

l = [1000, 298, 3579, 100, 200, -45, 900] n = 4 l.sort() print(l[-n:])

`