How to Return the Largest & Smallest Values From a Python List Using Heapq

Python

 1|  import heapq
 2|  
 3|  x = [1,2,3,4]
 4|  y = [3,4,5,6]
 5|  
 6|  #Returns a list containing the two largest elements from the list x
 7|  largest = heapq.nlargest(2,x)
 8|  
 9|  
10|  #Returns a list containing the two smallest elements from the list y
11|  smallest = heapq.nsmallest(2,y)
Did you find this snippet useful?

Sign up for free to to add this to your code library