How to Find the Smallest or Largest Items in a List in Python 


               


How to Find the Smallest or Largest Items in a List in Python



Python


In this article, we show how to find the smallest or largest items in a list in Python.

Using the heapq module in Python, we can find the smallest or largest number.

We go over this below.


How to Find the Smallest Items in a List

To find the smallest items in a list in Python using the heapq module, we use the heapq.nsmallest() function.

This is shown below.



First, we must import the heapq module.

After this, we create a list called numbers, which contains a variety of numbers.

We then create a variable named smallest. We assign this variable to the heapq.nsmallest() function.

Inside of this function, we specify 2 values. The first values is how many values you want to display. The second value is the list you are referring to (in this case, numbers).

If we display the smallest variable above, we get what is shown below.



Because we specified 2 as the number of units to show, it shows the smallest 2 numbers. If you specify 3, it would show the 3 smallest numbers, etc.


How to Find the Largest Items in a List

To find the largest items in a list in Python using the heapq module, we use the heapq.nlargest() function.

This is shown below.



Again, we must import the heapq module.

We have the same list of numbers that we had before.

We, again, specify 2 as the first parameter to the heapq.nlargest() function, so the program will show the 2 largest items (numbers) in the list.

If we display the largest variable above, we get what is shown below.



Because the 2 largest numbers are 12 and 10, these are the numbers that are shown.

Again, you can change how many of the largest items you want to show.

And this is how we can find the smallest or largest items in a list in Python.


Related Resources



HTML Comment Box is loading comments...