brown round fruit on stainless steel bowl
Photo by Sincerely Media on Unsplash

You are usually asked to get the largest or smallest element in a list, but it can also be the case that you are asked to also find more than just a single element, namely, a number of elements that are the largest, or the smallest in that list.

For example, let us assume that you are a teacher and you want to see the top three highest scores reached in a recent exam:

Now, if we want to get the top three largest elements in this list, we can use the module called heapq and use its methods:

We can similarly use nsmallest() method to find n smallest elements in a list:

Here is the complete example:


That’s basically it. I hope you find this useful.