Content · Programming · Python

Python heapq.nsmallest() Function: Usage and Examples

Retrieve the n smallest values or lowest-key records.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Retrieve the n smallest values or lowest-key records.

What You Will Learn


nsmallest(n, iterable, key=None) returns a list and works with generators as well as lists. For n=1, min() is often simpler.

Time complexity assumes a specific input structure. Include setup work such as sorting or building a lookup table when comparing complete solutions.

Step-by-Step Example


The example below makes the behavior visible with small input values that you can change safely.

from heapq import nsmallest
prices = [19, 5, 12, 7]
print(nsmallest(2, prices))

How the Example Works


  • The imports provide the standard-library tools used in the demonstration: heapq.
  • The variable prices holds the result of [19, 5, 12, 7]. Later lines use that value or inspect how it changes.
  • The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.

For the chosen input, the expression nsmallest(2, prices) prints [5, 7]. Compare that result with the rule above before you change the argument.

Expected output from the example:

[5, 7]

Another Example: Compare the Results


Try a second input and compare it with the first. Notice whether the result changes in type, value, order, or number of items.

from heapq import nsmallest
print(nsmallest(2, [3, 9, 1, 5]))

Expected output:

[1, 3]

When You Would Use This


This technique matters when a program handles larger queues, sorted records, or repeated lookups. Choose the data structure based on actual operations and the preconditions the algorithm requires. Verify boundary inputs before optimizing for speed.

Practice: Modify the Code


Select the three least expensive product offers.

Verify the changed output against the behavior described above, including the relevant invalid or boundary case.

For complete parameters and version details, consult the official Python documentation.

Common Beginner Mistakes


  • Assuming nsmallest() rearranges the original iterable in place.
  • Assuming the input is correctly sorted or arranged without checking the algorithm’s preconditions.

Key Takeaways


  • Retrieve the n smallest values or lowest-key records.
  • nsmallest(n, iterable, key=None) returns a list and works with generators as well as lists.
  • Apply this operation only after checking the assumptions and input conditions shown in the example.
Share this resourceSend this page to someone who may find it useful.