Python program to find N largest elements from a list

You can use the heapq.nlargest() function from the heapq library to find the N largest elements from a list. Here’s an example:

# Finding N largest elements from a list

import heapq

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
n = 3  # number of largest elements to find
largest_numbers = heapq.nlargest(n, numbers)
print(largest_numbers) # The output will be [10, 9, 8], the 3 largest elements in the list

This will output [10, 9, 8] which are the 3 largest elements in the given list.

You can also use the sorted() function in combination with slicing to get the same result:

# Finding N largest elements from a list

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
n = 3  # number of largest elements to find
largest_numbers = sorted(numbers, reverse=True)[:n]
print(largest_numbers) # The output will be [10, 9, 8], the 3 largest elements in the list

This will also output [10, 9, 8]

In both of these examples, the list of numbers is sorted in descending order and the first N elements are returned using slicing.

Leave a Comment