All Courses

Find the Largest and smallest items in a collection.

By Sajid, 2 years ago
  • Bookmark

To find the largest items in a collection and which module is used for this.

1 Answer

To find the largest items in a collection, heapq module has a function called nlargest , we pass it two arguments, the

first one is the number of items that we want to retrieve, the second one is the collection name:

import heapq
numbers = [1, 4, 2, 100, 20, 50, 32, 200, 150, 8]
print(heapq.nlargest(4, numbers)) # [200, 150, 100, 50]

Similarly, to find the smallest items in a collection, we use nsmallest function:

print(heapq.nsmallest(4, numbers)) # [1, 2, 4, 8]

Your Answer


Why You Should Learn Data Science in 2023?

Jun 8th (7:00 PM) 289 Registered
More webinars

Related Discussions

Running random forest algorithm with one variable

View More