Home »
Python »
Python programs
Python program to find N largest and smallest elements from the list
Python heapq.nlargest() and heapq.nsmallest() functions Examples: Here, we are going to learn how to find N largest and smallest elements?
Submitted by Yash Khandelwal, on April 13, 2019
Here, we learn how to find out the N largest and smallest elements from the list? Where, list and N given by the user, N may be any value but less than the list length.
Description:
There are two ways,
1. By defining a function:
Procedure:
- Define the function name largest_ele and smallest_ele.
- Pass two arguments in a function (l,n) : l is the list and n is the number of elements.
- Run the for loop n times
- In the loop find the maximum of the given list and append it to another list
- And after appending to another list remove the maximum element from the list
By the inbuilt module heapq module
If you are looking for the N smallest or largest items and N is small compared to the overall size of the collection, these functions provide superior performance.
- Import the heapq module
- Give the list
- Now use the function heapq.nlargest(n,l) and heapq.nsmallest(n,l) from the module to find the largest and the smallest numbers.
Python code:
# N largest and smallest element in a list
# by function and by the help of heapq module
#function to find n largest element
def largest_ele(l,n):
s=[]
for i in range(n):
s.append(max(l)) #append max of list in a new list
l.remove(max(l)) #remove max of list from the list
print('by largest_ele function: ',s)
#function to find n largest element
def smallest_ele(m,n):
t=[]
for i in range(n):
t.append(min(m))#append min of list in a new list
m.remove(min(m))#remove min of list from the list
print('by smallest_ele function: ',t)
l=[2,4,6,8,10]
m=[0,1,2,3,4,5,6]
n=2
largest_ele(l,n)
smallest_ele(m,n)
# using the inbuilt module function
# heapq.nlargest and heapq.nsmallest
import heapq
nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
print('BY heapq.nlargest: ',heapq.nlargest(3, nums)) # Prints [42, 37, 23]
print('BY heapq.nsmallest: ',heapq.nsmallest(3, nums)) # Prints [-4, 1, 2]
Output
by largest_ele function: [10, 8]
by smallest_ele function: [0, 1]
BY heapq.nlargest: [42, 37, 23]
BY heapq.nsmallest: [-4, 1, 2]
Note: The nlargest() and nsmallest() functions are most appropriate if you are trying to find a relatively small number of items. If you are simply trying to find the single smallest or largest item (N=1), it is faster to use min() and max().
TOP Interview Coding Problems/Challenges