Priority queues and sorted search
Use heapq and bisect without pretending every ordered operation is constant time.
Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.
Before you start
Learners who can read small Python functions and want to apply the listed foundations.
Explore the connected curriculum and preparation map
Lesson content version 2026-10-27. Suggested core budget: 14 minutes; optional deep dive: 12 more minutes. These are reading/practice estimates, not a timed test.
Suggested preparation and repair routes
If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.
Actual runtime and local-lab boundaries
Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.
Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.
Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.
- Explain heap order is partial order
- Apply search is not insertion
- Reason about pick the right workload
Heap order is partial order
A min-heap keeps the smallest item available at its root. It does not keep every position sorted.
Understand first
A scheduler repeatedly needs the next smallest priority, not a fully sorted report after every new arrival. A heap maintains enough order for that question.
Words you will see
- Heap invariant
- Each parent's priority is no greater than the priorities of its children.
- Root
- The smallest item, at list index zero in Python's min-heap representation.
- Tie-breaker
- A comparable secondary value that resolves equal priorities deterministically.
Read the partial-order promise
heapq uses an ordinary list as storage. heapify rearranges that list in place so the heap invariant holds. Reading heap[0] then inspects the minimum without removing it. heappop removes the smallest entry and restores the invariant for the remaining heap.
A parent being no greater than its children does not mean siblings or consecutive list positions are sorted. Do not iterate the underlying list as if that were priority order. Repeated heappop calls produce priority order by doing additional work.
A priority needs a complete comparison rule
Tuples compare from left to right. A (priority, sequence_number, job) entry compares the priority first, then an increasing number. If those first two fields distinguish all live jobs, comparison never needs to order the job payloads themselves.
Without a tie-breaker, equal priorities followed by dictionaries or other non-orderable payloads can raise TypeError. If equal-priority jobs should be first-in-first-out, the sequence number is a product rule rather than an incidental implementation convenience.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
heapq.heapify(jobs)Rearrange the existing storage into a valid min-heap.
print(jobs[0])Inspect the minimum without removal.
print(heapq.heappop(jobs))Remove that same minimum and repair the heap.
print(sorted(jobs))Create a sorted display of the remaining jobs, not an assertion that heap storage was sorted.
A min-heap guarantees the smallest item is at index zero; it does not keep every position sorted. heapq uses a list as storage. Push/pop cost O(log n), while inspecting the minimum is O(1). Use a monotonic tie-breaker when equal priorities contain objects that cannot be compared.
Partial order serves one selection question
Conceptual reasoning steps for the original example, not a live trace of your edited Python.
- MaintainEvery parent is no greater than its children.
- InspectThe root is a minimum.
- ConsumePop repairs the heap before the next selection.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Add a more urgent job.
Try: Call heapq.heappush(jobs, 0) before reading the root.
Zero becomes the next minimum without requiring a fully sorted list.
Keep the minimum while showing order.
Try: Compare sorted(jobs) with repeated heappop calls on jobs.copy().
Both can display sorted values while the original heap remains available.
Before you move on
If the root is the minimum, must the item at index 1 be the second-smallest value?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. Another branch may contain the next-smallest value. The heap invariant relates parents and children, not every consecutive position. Use heappop to select the next minimum correctly.
Search is not insertion
Binary search finds a position in an already sorted sequence. That position may be an insertion point, not an existing equal value.
Understand first
You may need the first score at least a threshold, a boundary around duplicates, or an exact-match check. Each question needs a different interpretation of the returned position.
Words you will see
- bisect_left
- Find the insertion boundary before existing equal values.
- bisect_right
- Find the insertion boundary after existing equal values.
- Sorted precondition
- The input already follows the same ordering used by the search.
Use the boundary, then decide what it means
For [10, 20, 20, 40], bisect_left(scores, 20) returns 1, before the first equal value. bisect_right returns 3, after both equals. For 30, the left boundary is also 3, even though no score equals 30. A valid insertion boundary is not proof of membership.
To check exact presence, first ensure index < len(scores), then compare scores[index] == target. The end boundary len(scores) is legitimate for insertion but invalid for a single-item read. Empty input therefore gives insertion position zero without containing an item.
A fast search does not make an insertion cheap
Binary search narrows a sorted range in O(log n) comparisons. Inserting into the middle of the Python list still moves later references and is O(n). bisect.insort does both jobs; it does not remove list movement costs.
The sorted-input precondition matters. Passing an arbitrary unsorted list does not make bisect sort it or promise a meaningful boundary. Decide who maintains order and how expensive comparisons or key extraction are before stating a total cost.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
print(bisect_left(scores, 20))The left boundary is 1, before both copies of 20.
print(bisect_right(scores, 20))The right boundary is 3, after the equal range.
index = bisect_left(scores, 30)Thirty would be inserted before 40 at position 3.
print(index < len(scores) and scores[index] == 30)The safe bounds-and-equality test reports no exact match.
bisect locates an insertion position in O(log n) comparisons in an already sorted sequence. Inserting into the underlying Python list still shifts references and costs O(n). A search result must be checked before interpreting it as an exact match.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Search past the end.
Try: Change the target 30 to 99 in both places.
The index becomes len(scores); short-circuiting avoids the invalid list read.
Insert while preserving order.
Try: Use bisect.insort(scores, 30), then print(scores).
The list becomes [10, 20, 20, 30, 40], with movement work in addition to search.
Before you move on
What does bisect_left([], 8) return, and may you immediately read that position?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
It returns the insertion boundary 0. The empty list has no position 0 to read, so check the boundary against the list length first.
Pick the next job and locate a score
Use a heap for repeated next-priority selection and a sorted sequence for ordered boundaries. They provide different invariants and cannot be substituted blindly.
Understand first
The next urgent job and a score's insertion boundary are separate operations. A small worked program makes each result's meaning explicit.
Words you will see
- Minimum priority
- Here the numerically smallest priority, not the largest importance label.
- In-place construction
- Rearranging the supplied list rather than returning a new collection.
- Leftmost boundary
- The earliest position at which the target can be inserted without breaking sorted order.
Trace each data structure's promise
The job list begins with priorities 3, 1 and 2. heapify mutates the list into a valid heap. heappop then returns (1, 'urgent') because priority is compared first. The remaining list still represents a heap, not a general sorted report.
The score list is independently sorted already. Searching 20 finds index 1, before both equal entries. Searching absent 30 finds index 3, before 40. These returned numbers are boundaries, not values extracted from the list.
The simplest data structure depends on frequency
For one final report, sorted(jobs) may express the goal more clearly than maintaining a heap. For many arrivals interleaved with next-job selections, pushes and pops update partial order without sorting everything each time.
No job tie occurs in this example. If you add equal priorities with non-orderable payloads, declare a tie-breaking rule first. Do not hide a TypeError by silently discarding an event or changing its priority.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
heapq.heapify(jobs)Build a min-heap in the existing job list.
print(heapq.heappop(jobs))Remove the numerically lowest priority job.
print(bisect_left(scores, 20))Find the first possible position of an equal score.
print(bisect_left(scores, 30))Find a valid insertion point even though 30 is absent.
The heap selects minimum priority; bisect_left returns the leftmost insertion position, including when a value is absent.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Give batch the smallest priority.
Try: Change the batch priority from 3 to 0.
Batch is selected first because priority values, not the job label, define this ordering.
Search for an existing endpoint.
Try: Replace the search target 30 with 40.
The boundary remains 3, now selecting an existing equal score.
Before you move on
Can bisect search the heap's backing list correctly just because the smallest entry is at index zero?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
Not generally. Bisect requires the whole sequence to be sorted according to its comparison. A heap provides a weaker parent/child relation and need not satisfy that precondition.
Where this idea earns its place
A priority queue answers which item should be processed next; a sorted search answers where a key belongs in an already ordered sequence. These are different contracts. Use a heap for repeated minimum extraction and bisect for boundary location, while preserving the assumption that the compared keys have a consistent ordering.
Follow the mechanism step by step
A heap maintains a parent/child invariant sufficient to expose the minimum, not a fully sorted list. heapify builds that structure in linear time; push/pop adjust along a tree path. bisect repeatedly halves an index interval, but locating a position does not move or allocate the item itself.
Work through a concrete application
For jobs, store a priority and a monotonic tie-breaker before an opaque task object so equal priorities do not force Python to compare unorderable tasks. For a sorted score list, find the left boundary, then verify both that the index is in range and that the value matches if exact membership is required.
Failure cases and misleading shortcuts
Mutating a stored priority without restoring the heap invariant can make future extraction wrong. Sorting or modifying the backing list arbitrarily has the same risk. A bisect result for a missing key is a valid insertion point, not proof the key exists. Duplicate keys require a declared left/right-boundary policy.
Cost, ownership and alternatives
Heap push/pop costs O(log n) and root inspection O(1); retained heap entries consume O(n). bisect uses O(log n) comparisons, but list insertion still shifts O(n) references. For top-k work, a bounded heap may avoid retaining and sorting all n items. Include comparison-key cost when keys are expensive.
Verify the contract
Test empty heaps, duplicate priorities, opaque task payloads and stale priority updates. For bisect, test before-first, after-last, exact match and repeated equal keys. Verify results against a simple sorted reference on small generated data before relying on a more complex heap-based optimisation.
Transfer question: How can changing job priorities be supported without mutating heap entries in place?
Insert a new version and mark old versions stale, then discard stale entries when popped. Track the authoritative version separately and plan compaction so stale entries do not grow without bound. Alternatively use a data structure explicitly supporting indexed priority updates.
Can you explain it?
Try from memory. Feedback stays on this page and does not award judged progress.
Rebuild: Pick the next job and locate a score
Without copying the worked code, reproduce its observable contract: The heap selects minimum priority; bisect_left returns the leftmost insertion position, including when a value is absent. Then change one boundary input and explain the result.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Guided practice and transfer
These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.
A short function primer before you begin
def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.
return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Guided: return numeric priority order
Consume a private heap instead of editing the caller's list.
The contract
- Input is a list of integers.
- Return a new list in nondecreasing order with all duplicates preserved.
- Preserve the input; empty input gives an independent empty list.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- sorted result
assert priority_order([3, 1, 2]) == [1, 2, 3], "Select every minimum in turn"
- duplicates
assert priority_order([2, 1, 2]) == [1, 2, 2], "Keep equal occurrences"
- negative
assert priority_order([0, -2, 1]) == [-2, 0, 1], "Allow negative priorities"
- empty
assert priority_order([]) == [], "Empty input has no priorities"
- ownership
values = [3, 1, 2] result = priority_order(values) assert isinstance(result, list) and result == [1, 2, 3] and values == [3, 1, 2] and result is not values, "Preserve source order"
- all values
assert priority_order([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5], "Do not return one minimum only"
Is this always better than sorted?
No. A one-time sorted report is often clearer with sorted. This exercise demonstrates private heap consumption: O(n log n) total selection time, O(n) copied heap/result storage, with bounded comparisons.
Guided: find the first exact sorted match
Turn an insertion boundary into a checked lookup.
The contract
- Input values is an already sorted list of integers; target is an integer.
- Return the first equal index, or -1 if absent.
- Preserve the input; empty input and targets after the end are valid absent cases.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- duplicates first
assert first_match([10, 20, 20, 40], 20) == 1, "Choose the first equal index"
- gap absent
assert first_match([10, 20, 40], 30) == -1, "A boundary is not a match"
- past end
assert first_match([1, 2], 9) == -1, "Do not read past the end"
- empty
assert first_match([], 1) == -1, "No values means absent"
- first item
assert first_match([1, 2], 1) == 0, "Index zero is valid"
- source preserved
values = [1, 3, 3] assert first_match(values, 3) == 1 and values == [1, 3, 3], "A search must not edit input"
Why are both a bounds test and an equality test needed?
A boundary can be at the end or before an unequal value. With an already sorted input, binary search uses O(log n) comparisons and O(1) extra space; sorting inside the function would change both its cost and ownership contract.
Transfer: preserve arrival order on priority ties
The new requirement is a stable priority queue, not alphabetical ordering of job labels.
The contract
- Input is a list of (integer priority, string label) pairs.
- Return labels ordered by ascending priority; equal priorities keep input order.
- Preserve input and repeated labels; empty input gives a new empty list.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- priority
assert stable_job_order([(3, "batch"), (1, "urgent")]) == ["urgent", "batch"], "Select ascending priority"
- tie order
assert stable_job_order([(1, "z"), (1, "a")]) == ["z", "a"], "Keep arrival order on ties"
- mixed ties
assert stable_job_order([(2, "x"), (1, "z"), (1, "a")]) == ["z", "a", "x"], "Apply both priority and stability"
- duplicates
assert stable_job_order([(1, "x"), (1, "x")]) == ["x", "x"], "Keep repeated jobs"
- empty
assert stable_job_order([]) == [], "An empty queue has no labels"
- ownership
jobs = [(2, "b"), (1, "a")] result = stable_job_order(jobs) assert isinstance(result, list) and result == ["a", "b"] and jobs == [(2, "b"), (1, "a")] and result is not jobs, "Preserve caller jobs"
Why is (priority, label) alone insufficient?
On equal priorities it would sort by label rather than arrival order. The unique index implements the declared tie policy. Building then draining n jobs uses O(n log n) time and O(n) additional storage with bounded-cost comparisons.
Core route complete.
If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.
Save your core reading milestoneChanging priorities
Changing a stored priority can invalidate a heap. A versioned replacement policy can skip stale entries, but stale storage still needs a retention policy.
Understand first
A scheduler may reprioritise a waiting job. The heap does not automatically observe an external change to a task's desired priority.
Words you will see
- Stale entry
- An older queued version no longer representing the current job state.
- Version
- A generation identifier used to distinguish updates.
- Lazy invalidation
- Leaving an old entry in storage and skipping it when encountered later.
Repair the invariant rather than mutating an arbitrary slot
If you replace a priority in a backing-list position without repair, the smallest value might no longer reach the root. Re-heapifying the whole list is one simple O(n) repair, but repeated updates can need a more deliberate design.
An alternative pushes a new version while recording which version is live for each job. When an old entry reaches the root, compare its version with the live record and skip it if stale. This is a declared job-identity policy, not something heapq supplies automatically.
Lazy does not mean memory-free
Each stale record occupies storage until popped or removed in a rebuild. A long-lived system with repeated updates and few removals can accumulate many records. Measure and bound that retention with explicit cleanup thresholds rather than claiming the heap size equals the number of live jobs.
For a bounded top-k problem, a heap of k candidates can use O(k) retained entries instead of sorting every item. The direction of its root rule must match whether you retain smallest or largest values; a copied scheduler pattern can implement the wrong policy.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
live = {"api": 1, "worker": 0}Declare api version 1 as current; version 0 is stale.
priority, version, job = heapq.heappop(heap)Pop priority 1 first, even though it is stale.
if live.get(job) == version:Only the current version is eligible for selection.
print(len(heap))One worker entry remains after both api entries were consumed.
Mutating a priority in place can invalidate the heap invariant. A common approach pushes a new version and marks old entries stale, but stale records consume memory and need cleanup. A bounded top-k heap can reduce storage to O(k) instead of sorting all n items.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Make the old version current.
Try: Change live["api"] to 0.
Priority 1 api is now accepted.
Remove the invalidation policy.
Try: Print every popped entry without the version condition.
Both versions appear, demonstrating why identity policy is separate from heap ordering.
Before you move on
If updates are pushed but jobs are rarely popped, what happens to old queued versions?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
They remain retained and can grow without bound. Lazy invalidation needs a cleanup/retention policy, even though each individual push is efficient.
Pick the right workload
Choose an algorithm for the sequence of questions you actually ask. Search cost, movement cost and comparison cost all contribute to total work.
Understand first
A function can use binary search and still be slow because it repeatedly inserts into a list. A heap can be the wrong complexity trade-off for one final sorted answer.
Words you will see
- n / k
- Here n is the input length and k is the number of retained candidates.
- Comparison cost
- The work needed to compare two keys or values.
- Workload
- The mix and frequency of operations, not just one call in isolation.
Trace the helper operation inside the loop
insort searches for the insertion boundary, then shifts entries to make room. Repeating that for n arbitrary arrivals can take quadratic total movement. For a one-time report, collecting values and sorting once is often clearer and asymptotically better.
A heap supports each push or pop in O(log n) comparison steps and minimum inspection in O(1). heapify builds a heap in O(n). Those are growth descriptions under bounded-cost comparisons, not measured milliseconds or claims that Python object comparison is free.
Protect the caller's ownership promise
heapify mutates its list; sorted returns a new list. If the caller needs its original input unchanged, copy before heapifying. A copy adds O(n) work and storage, which should be included rather than omitted because the interesting operation was logarithmic.
For returning k smallest values, heapq.nsmallest expresses the policy directly. For a membership test in an already sorted list, bisect plus an equality/bounds check may be enough. Do not introduce priority machinery where a simpler static answer meets the requirement.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
report = sorted(values)Build a new sorted list, preserving the input order.
index = bisect_left(report, 25)Search only for the insertion boundary, returning 2.
insort(report, 25)Search and move later entries in the result list.
print(report)The result includes 25 in order; the original values list is still unchanged.
For one final sorted report, sorted may be clearer. For repeated next-minimum selection, use a heap. For many list insertions, bisect does not remove movement costs. Document comparator/key costs rather than treating comparisons as always free.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Insert an endpoint value.
Try: Use insort(report, 99).
Appending at the end needs less shifting, but arbitrary insertion still has a linear worst case.
Compare static selection.
Try: Print report[:2] after sorting.
The first two values solve a static smallest-two request without maintaining a separate scheduler.
Before you move on
If a caller needs one final sorted report, must you use a heap because priorities are involved?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. sorted can directly express the requested report. A heap is especially useful for interleaved updates and next-minimum selections; choose by workload and ownership needs.
Make the explanation your own.
Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.
Take a versioned study copy
Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.
Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.
Make this a milestone.
Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.