Overview
- The nlargest() function of the Python module heapq returns the specified number of largest elements from a Python iterable like a list, tuple and others.
- The function nlargest() can also be passed a key function that returns a comparison key to be used in the sorting.
Example
# Example Python program that finds the largest n elements
# from a Python iterable
import heapq
iterable = [6,1,7,9,3,5,4]
selectCount = 3
largests = heapq.nlargest(selectCount, iterable)
print(largests)Output
[9, 7, 6]Example – nlargest() invoked with a comparison key function
# Example Python program that finds the largest n elements
# from a Python iterable
import heapq
# Define a function that returns a comparison key for city objects
def sortkey(city):
return city.population
# Define a City class
class City:
def __init__(self, id, name, population):
self.id = id
self.name = name
self.population = population
def __str__(self):
return self.name
# Create instances of City class
c1 = City(1, "City1", 1500)
c2 = City(2, "City2", 1100)
c3 = City(3, "City3", 1700)
c4 = City(4, "City4", 1200)
c5 = City(5, "City5", 1600)
# Make a list of City instances
cities = [c1, c2, c3, c4, c5]
# Find three most populated cities
mostPopulated = heapq.nlargest(3, cities, key = sortkey)
# Print three most populated cities
for city in mostPopulated:
print(city)Output
City3
City5
City1